OkHttp 和 AsyncHttpClient 性能对比

OkHttp: http://square.github.io/okhttp/
AsyncHttpClient: https://github.com/AsyncHttpClient/async-http-client

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import com.google.common.collect.Lists;
import okhttp3.*;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
/**
* author: sunshow.
*/
public class HttpClientTest {
private static final String fetchUrl = "https://www.baidu.com";
private final OkHttpClient client = new OkHttpClient();
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
public void fetchByOkhttpAsync(CountDownLatch latch) throws Exception {
Request request = new Request.Builder()
.url(fetchUrl)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
response.body().string();
latch.countDown();
}
});
}
public void fetchByOkhttpSync() throws Exception {
Request request = new Request.Builder()
.url(fetchUrl)
.build();
Response response = client.newCall(request).execute();
response.body().string();
}
public void testFetchByAsyncHttpClient(int count) throws Exception {
long t = System.currentTimeMillis();
List<Future<org.asynchttpclient.Response>> futureList = Lists.newArrayList();
for (int i = 0; i < count; i++) {
futureList.add(asyncHttpClient.prepareGet(fetchUrl).execute());
}
for (Future<org.asynchttpclient.Response> future : futureList) {
org.asynchttpclient.Response response = future.get();
response.getResponseBody();
}
t = System.currentTimeMillis() - t;
System.out.println("AsyncHttpClient took: " + t + " ms");
}
public void testFetchByOkhttpAsync(int count) throws Exception {
CountDownLatch latch = new CountDownLatch(count);
long t = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
fetchByOkhttpAsync(latch);
}
latch.await();
t = System.currentTimeMillis() - t;
System.out.println("OkHttp Async took: " + t + " ms");
}
public void testFetchByOkhttpSync(int count) throws Exception {
long t = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
fetchByOkhttpSync();
}
t = System.currentTimeMillis() - t;
System.out.println("OkHttp Sync took: " + t + " ms");
}
@Test
public void testFetch() throws Exception {
int count = 1000;
testFetchByOkhttpSync(count);
testFetchByOkhttpAsync(count);
testFetchByAsyncHttpClient(count);
}
}

测试结果:

1
2
3
OkHttp Sync took: 13018 ms
OkHttp Async took: 3185 ms
AsyncHttpClient took: 4980 ms
显示 Gitment 评论