http 请求合并编程

HTTP请求合并是指在某些场景如业务需求一次性发送多个HTTP时可以将所有HTTP URL进行批量请求,当所有HTTP请求结束时会触发响应回调。因为是同一时间发送所有请求,最终耗时由最后响应的HTTP服务决定。

代码示例

@Test
public void testRxIoHttpMerge() throws Exception {
    final EventLoopGroup group = new EventLoopGroup(1);
    group.start();
    CountDownLatch latch = new CountDownLatch(1);

    long start = System.currentTimeMillis();
    final String url1 = "https://www.baidu.com";
    final String url2 = "http://www.163.com";
    final String url3 = "https://www.taobao.com";
    final String url4 = "https://www.jd.com";
    final String url5 = "http://www.wayken.icoc.cc";
    final String url6 = "http://jz.fkw.com";
    RxIo<HttpAnswer> http1 = RxIo.http(group, url1);
    RxIo<HttpAnswer> http2 = RxIo.http(group, url2);
    RxIo<HttpAnswer> http3 = RxIo.http(group, url3);
    RxIo<HttpAnswer> http4 = RxIo.http(group, url4);
    RxIo<HttpAnswer> http5 = RxIo.http(group, url5);
    RxIo<HttpAnswer> http6 = RxIo.http(group, url6);

    RxIo<HttpAnswer> batch = RxIo.merge(http1, http2, http3, http4, http5, http6);
    batch.subscribe(new IoSubscriber<HttpAnswer>() {
        @Override
        public void onNext(HttpAnswer response) {
            System.err.println("----------------- " + Thread.currentThread() + response.getUrl() + " ----------------");
            System.out.println(response.getHeaders());
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }

        @Override
        public void onCompleted() {
            System.out.println("complete");
            latch.countDown();
            group.shutdown();
        }
    }).start();
    latch.await();
    long exeTime = System.currentTimeMillis() - start;
    System.err.println("----------------- " + Thread.currentThread() + " execute time:" + exeTime + " ----------------");
}