在okhttp中使用http2时,为什么对同一主机的多个请求不只使用一个connectoin [英] When using http2 in okhttp, why multi requests to the same host didn't use just one connectoin

查看:66
本文介绍了在okhttp中使用http2时,为什么对同一主机的多个请求不只使用一个connectoin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试 okhttp 的 http2 功能.我以异步方式向同一主机发出多个请求.但是,我发现它涉及多个连接,因为协议是h2,它应该只使用一个连接,对吧?代码如下.啊,我用的是okhttp2.5

I would like to test okhttp's http2 function. And I make multi requsts to same host in async style. But, I found that, it involved multi connections, since the protocol is h2, It should use just one connection, right? The code is below. Ah, I'm using okhttp2.5

public class Performance {
    private final OkHttpClient client = new OkHttpClient();
    private final Dispatcher dispatcher = new Dispatcher();
    private final int times = 20;

    public Performance(){
        dispatcher.setMaxRequestsPerHost(2);
        client.setDispatcher(dispatcher);

        // Configure the sslContext
        // MySSLSocketFactory mySSLSocketFactory = new MySSLSocketFactory();
        // client.setSslSocketFactory(mySSLSocketFactory);
        // client.setHostnameVerifier(new HostnameVerifier() {
        //     public boolean verify(String s, SSLSession sslSession) {
        //         return true;
        //     }
        // });
    }
    public void run()throws Exception{
        for(int i=0; i<times; i++) {
            Request request = new Request.Builder()
                .url("https://http2bin.org/delay/1")
                .build();
            client.newCall(request).enqueue(new Callback() {
                public void onFailure(Request request, IOException e) {
                    e.printStackTrace();
                }

                public void onResponse(Response response) throws IOException {
                    System.out.println(response.headers().get("OkHttp-Selected-Protocol"));
                }
            });
        }
    }
    public static void main(String[] args)throws Exception{
        Performance performance = new Performance();
        performance.run();
    }
}

推荐答案

一个错误 在 OkHttp 中,多个并发请求各自创建自己的套接字连接,而不是协调共享连接.这仅在同时创建连接时发生.通过在第二次连接之前产生 500 毫秒来解决.

There's a bug in OkHttp where multiple simultaneous requests each create their own socket connection, rather than coordinating a shared connection. This only happens when the connections are created simultaneously. Work around by yielding 500ms before the 2nd connection.

这篇关于在okhttp中使用http2时,为什么对同一主机的多个请求不只使用一个connectoin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆