http 请求编程

HTTP请求是微服务开发中最常见的编程场景,如请求微信授权、支付宝支付接口等,本文档介绍如何通过RxIo.http来实现基于HTTP的异步编程方式。

代码示例

public static void testRxIoHttpExecutor() throws Exception {
    // 初始化EventLoop网络引擎,注意最好全局单例
    final EventLoopGroup group = new EventLoopGroup(4);
    group.start();

    long start = System.currentTimeMillis();
    final String url1 = "http://www.baidu.com";
    // 发送HTTP请求,同时快速释放网络阻塞
    RxIo.http(group, url1).map(new IoFunction<HttpAnswer, String>() {
        @Override
        public String call(HttpAnswer resp) throws IOException {
            System.err.println("----------------- Map1 " + Thread.currentThread() + url1 + " ----------------");
            System.out.println(resp.getHeaders().toString());
            return resp.getContent();
        }
    }).subscribe(new IoSubscriber<String>() {
        // 当产生网络数据响应时的数据流处理
        @Override
        public void onNext(String response) {
            System.err.println("----------------- Subscribe " + Thread.currentThread() + url1 + " ----------------");
            System.out.println(response);
            group.shutdown();
        }

        @Override
        public void onCompleted() {
            System.out.println("execute complete");
            group.shutdown();
        }

        @Override
        public void onError(Throwable e) {
            System.err.println("exception caught");
            e.printStackTrace();
            group.shutdown();
        }
    }).start();
    long exeTime = System.currentTimeMillis() - start;
    System.err.println("----------------- " + Thread.currentThread() + " execute time:" + exeTime + " ----------------");
}