在okhttp中使用http2时,为什么对同一主机的多个请求不只使用一个connectoin [英] When using http2 in okhttp, why multi requests to the same host didn't use just one connectoin
本文介绍了在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();
}
}
推荐答案
有一个错误
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屋!
查看全文