java socket keep alive很慢,重新打开socket更快

fab*_*ien 2 java sockets performance keep-alive

我试图想出一个简单的HTTP客户端的java实现,它保持套接字打开并重用它来查询同一主机上的其他(或相同)URL.

我有一个使用java.net.Socket的简单实现,但不知何故,当我保持套接字打开时的性能比我不断创建一个新的更糟糕.

结果首先,完整的可执行代码如下:

使用KeepAlive:从迭代#2开始变慢

> java -server -Xms100M -Xmx100M -cp . KeepAlive 10 true
--- Warm up ---
18
61
60
60
78
62
59
60
59
60
Total exec time: 626
--- Run ---
26
59
60
61
60
59
60
60
62
58
Total exec time: 576
Run Code Online (Sandbox Code Playgroud)

每次重新创建套接字会产生更好的结果:

> java -server -Xms100M -Xmx100M -cp . KeepAlive 10 false
--- Warm up ---
188
34
39
33
33
33
33
33
34
33
Total exec time: 494
--- Run ---
33
35
33
34
44
34
33
34
32
34
Total exec time: 346
Run Code Online (Sandbox Code Playgroud)

KeepAlive.java(独立,无依赖)

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

public class KeepAlive {

    private static final String NL = "\r\n";
    private static final int READ_SIZE = 1000;
    private Socket socket;
    private DataOutputStream writer;
    private BufferedReader reader;

    public static void main(String[] args) throws Exception {
        if (args.length == 2) {
            KeepAlive ka = new KeepAlive();
            System.out.println("--- Warm up ---");
            ka.query(Integer.parseInt(args[0]), args[1].equals("true"));
            System.out.println("--- Run ---");
            ka.query(Integer.parseInt(args[0]), args[1].equals("true"));
        } else {
            System.out.println("Usage: keepAlive <n queries> <reuse socket>");
        }
    }

    private void query(int n, boolean reuseConnection) throws Exception {
        long t0 = System.currentTimeMillis();
        if (reuseConnection) {
            open();
            for (int i = 0; i < n; i++) {
                long tq0 = System.currentTimeMillis();
                query();
                System.out.println(System.currentTimeMillis() - tq0);
            }
            close();
        } else {
            for (int i = 0; i < n; i++) {
                long tq0 = System.currentTimeMillis();
                open();
                query();
                close();
                System.out.println(System.currentTimeMillis() - tq0);
            }
        }
        System.out.println("Total exec time: " + (System.currentTimeMillis() - t0));
    }

    private void open() throws Exception {
        socket = new Socket();
        socket.setKeepAlive(false);
        socket.connect(new InetSocketAddress("example.org", 80));
        writer = new DataOutputStream(socket.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    private void query() throws Exception {
        StringBuilder req = new StringBuilder();
        req.append("GET / HTTP/1.1").append(NL);
        req.append("Host: example.org").append(NL);
        req.append("Connection: Keep-Alive").append(NL);
        req.append(NL);
        String reqStr = req.toString();

        long t0 = System.currentTimeMillis();
        writer.writeBytes(reqStr);
        writer.flush();

        String line;
        int contentLength = 0;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("Content-Length: ")) {
                contentLength = Integer.parseInt(line.substring(16));
            }
            if (line.equals("")) {
                char[] buf = new char[contentLength];
                int offset = 0;
                while (offset < contentLength) {
                  int len = contentLength - offset;
                  if (len > READ_SIZE) {
                    len = READ_SIZE;
                  }
                  int ret = reader.read(buf, offset, len);
                  if (ret == -1) {
                    System.out.println("End of stream. Exiting");
                    System.exit(1);
                  }
                  offset += ret;
                }

                break;
            }
        }
    }

    private void close() throws Exception {
        writer.close();
        reader.close();
        socket.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我很确定:

  1. Web服务器很难快速处理新请求(HTTP Keep Alive和TCP保持活动状态)

  2. 我使用缓冲读卡器的方式有问题,因为这是所有时间都丢失的地方,但看着其他可用的方法(我尝试了一些),我找不到我需要做什么来解决这个问题...

知道如何让这项工作更快?也许在服务器本身改变配置?...


正如下面的apangin所解释的那样,较慢的性能是由Nagle的算法引起的,该算法默认启用.使用setTcpNoDelay(true),我得到更新的以下perfs:

没有保持活力:

java -server -Xms100M -Xmx100M -cp . KeepAlive 10 false
--- Warm up ---
49
22
25
23
23
22
23
23
28
28
Total exec time: 267
--- Run ---
31
23
23
24
25
22
23
25
33
23
Total exec time: 252
Run Code Online (Sandbox Code Playgroud)

保持活力:

java -server -Xms100M -Xmx100M -cp . KeepAlive 10 true
--- Warm up ---
13
12
12
14
11
12
13
12
11
12
Total exec time: 168
--- Run ---
14
12
11
12
11
12
13
11
21
28
Total exec time: 158
Run Code Online (Sandbox Code Playgroud)

所以在这里,我们可以看到,对于每次迭代,保持活动版本的性能远远优于非保持活动版本,并且还可以比较总执行时间.:)

apa*_*gin 8

这是Nagle算法的效果.它会延迟发送TCP数据包以预期更多的传出数据.

Nagle算法交互严重与TCP延迟确认写-写-读场景.这正是你的情况,因为writer.writeBytes(reqStr)逐字节发送一个字符串.

现在您有两个选项来修复该行为:

  1. 使用socket.setTcpNoDelay(true)禁用Nagle算法;
  2. 在一次操作中发送完整的请求: writer.write(reqStr.getBytes());

在这两种情况下,重用的连接预计会更快.

  • 你是否会为你的删除投票辩护(除了个人的反感)? (2认同)