文章目录
1、测试
测试环境:
- win7 个人电脑;
- Server 是 SpringBoot web server;
client 端代码(默认为长连接):
RestTemplate rest = new RestTemplate();
for (int i = 0; i < 1000;i++){
rest.postForObject("http://localhost:8080/ailysis/scenario/test", Strings.repeat("a", 1000), Object.class);
}
client 端代码(短连接):
for (int i = 0; i < 1000;i++){
try {
HttpURLConnection connection = (HttpURLConnection)new URL("http://localhost:8080/ailysis/scenario/test").openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setRequestProperty("Connection-type", "application/json");
connection.setRequestProperty("Connection", "Close");
OutputStream outputStream=connection.getOutputStream();
outputStream.write(JSONBuilder.object("content", Strings.repeat("a", 1000).toJSONString().getBytes()));
outputStream.flush();
outputStream.close();
System.out.println(connection.getResponseCode());
} catch (IOException e) {
...
}
}
server 端代码:
@RequestMapping("/test")
public ResponseEntity<Integer> test(HTTPServletRequest request){
return new ResponseEntity<>(request.getContengLength(), HttpStatus.OK)
}
| 请求内容长度 | 发送次数 | 局域网 (ms) | 本地访问 (ms | 长连接 |
|---|---|---|---|---|
| 1000 | 1 | 271 | 219 | True |
| 1000 | 1000 | 4754 | 3297 | True |
| 10000 | 1000 | 5345 | 3080 | True |
| 1000 | 10000 | 35939 | 21930 | True |
| 10000 | 10000 | 32377 | 22430 | True |
几点说明:
- 以上情况,RestTemplate 会在相同的连接上发送 HTTP 数据包,也就是所谓的长连接;
- 时间消耗基本上跟 HTTP 请求次数相关;HTTP 协议是个很重的协议,比如,TCP 空报文的总大小为 54 字节(54 = 14+20+20),分别为链路层报文头 14 = 6 + 6 + 2,ip 报文头 20 字节,tcp 报文头 20,有时候 tcp 会带一些选项参数,一般十几个字节。但是一个空 HTTP 报文,基本都大于 300 字节。所以说,HTTP 是个很重的传输协议,只不过现在网速越来越快了,传输效率不再是制约系统的瓶颈了,HTTP 才得以大行其道;
- 最后发现,长短连接对该场景,影响不是很大;因为是本地或局域网,tcp 三次握手所消耗的时间很少,如果在互联网上,另当别论。
- 测试中不涉及服务器的并发处理,仅测试单连接的处理情况;
2、wireshark 数据流
1、单个 HTTP 连接建立到关闭的 wireshark 抓包视图:
2、长连接上发送两个 HTTP 数据包的视图:
在长连接模式,尽管发送了两个 HTTP,但是只建立了一个 TCP 连接:
21.0.0.43:20082 < = > 30.0.24.111:8080
3、使用短连接发送两个 HTTP 包的视图:
可以清楚的看到,有两次建立连接和释放连接的过程,建立了两条 TCP 连接:
21.0.0.43:27575 < = > 30.0.24.111:8080-
21.0.0.43:27578 < = > 30.0.24.111:8080
4、长连接上发送多个 HTTP 包的视图: