【发布时间】:2015-12-14 00:14:46
【问题描述】:
我想测试一下okhttp的http2功能。而且我以异步方式向同一主机发出多个请求。但是,我发现,它涉及到多连接,因为协议是h2,它应该只使用一个连接,对吧? 代码如下。 啊,我用的是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();
}
}
【问题讨论】:
-
请说明您如何知道您的请求通过多个连接。
-
我得到的结论有以下几个原因: 1. 修改调度器的 maxRequestsPerHost 时,结果会相应地发生变化,这就是我使用 /delay/1 路径进行测试的原因。 maxRequestsPerHost 表示连接数或请求数,尽管多个请求可以在一个连接中执行? ; 2.我用/get等其他路径和HTTP1.1的性能对比,不管我设置多少请求,似乎都没有性能差异。
-
您能确认您获得的是 HTTP/2 连接吗?请注意,您需要桌面上的 Jetty-ALPN。
-
是的,我可以。 response.headers().get("OkHttp-Selected-Protocol") 显示使用的协议,我得到了 h2。我已经使用 -Xbootclasspath/p:C:/Users/zfz/.m2/repository/org/mortbay/jetty/alpn/alpn-boot/8.1.4.v20150727/alpn-boot- 添加了 Jetty-ALPN 支持8.1.4.v20150727.jar 在 VM 选项中。