• notice
  • Congratulations on the launch of the Sought Tech site

What should I do if the HttpClient always times out?

Timeout Meaning

Sorry, there is no total timeout, there are several different timeouts:

  1. The Connection Timeout (http.connection.timeout) – the time to establish the connection with the remote host

  2. the Socket Timeout (http.socket.timeout) – the time waiting for data – after establishing the connection; maximum time of inactivity between two data packets

  3. Connection pool timeout the Connection Manager Timeout (http.connection-manager.timeout) – the time to wait for a connection from the connection manager/pool

HttpClient v4.3 configuration timeout

Configure Timeouts Using the New 4.3. Builder
The fluent, builder API introduced in 4.3 provides the right way to set timeouts at a high level:

int timeout = 5; RequestConfig config = RequestConfig.custom() 
  .setConnectTimeout(timeout * 1000) 
  .setConnectionRequestTimeout(timeout * 1000) 
  .setSocketTimeout(timeout * 1000).build(); CloseableHttpClient client = 
  HttpClientBuilder.create().setDefaultRequestConfig( config).build()

That is the recommended way of configuring all three timeouts in a type-safe and readable manner.

How to simulate a connectTimeout

Artificially create a connection timeout error

Connect to a non-routable IP address, such as 10.255.255.1.

Request retry handler strategy

1.5.4. Request retry handler

HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { 
    public boolean retryRequest( 
            IOException exception, 
            int executionCount, 
            HttpContext context) { 
        if (executionCount >= 5) { 
            // Do not retry if over max retry count 
            return false; 
        } 
        if (exception instanceof InterruptedIOException) { 
            // Timeout 
            return false; 
        } 
        if (exception instanceof UnknownHostException) { 
            // Unknown host 
            return false; 
        }
        if (exception instanceof ConnectTimeoutException) { 
            // Connection refused 
            return false; 
        } 
        if (exception instanceof SSLException) { 
            // SSL handshake exception 
            return false; 
        } 
        HttpClientContext clientContext = HttpClientContext.adapt(context); 
        HttpRequest request = clientContext.getRequest(); 
        boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); 
        if (idempotent) { 
            // Retry if the request is considered idempotent 
            return true; 
        } 
        return false; 
    } };CloseableHttpClient httpclient = HttpClients.custom() 
        .setRetryHandler(myRetryHandler) 
        .build();

java tcp/ip exception

Online Questions! ----------ORG.APACHE.CATALINA.CONNECTOR.CLIENTABORTEXCEPTION:JAVA.IO.IOEXCEPTION:BROKEN PIPE

java.net.SocketTimeoutException.

This exception is more common, socket timeout. Generally, there are two places to throw this, one is connect, the timeout parameter is determined by the latter in connect(SocketAddress endpoint, int timeout), and there is setSoTimeout(int timeout), which is set to read the timeout period. They are set to 0 to indicate infinity.

java.net.BindException: Address already in use: JVM_Bind

This exception occurs when the server performs the new ServerSocket(port) or socket.bind(SocketAddress bindpoint) operation.
Reason: A port same as port has been started and is listening. At this point, use the netstat -an command to see a port in the Listending state. Just find a port that is not occupied to solve this problem.

java.net.ConnectException: Connection refused: connect

This exception occurs when the client performs the new Socket(ip, port) or socket.connect(address, timeout) operation. Reason: The machine with the specified ip address cannot be found (that is, the route from the current machine to the specified ip does not exist), Or the ip exists, but the specified port cannot be found to listen on. You should first check whether the ip and port of the client are written incorrectly. If they are correct, ping the server from the client to see if the ping is successful. Whether the server-side program that listens to the specified port is started.

java.net.SocketException: Socket is closed

This exception can occur on both client and server. The reason for the exception is that the network connection is read and written after the user has actively closed the connection (calling the close method of Socket).

java.net.SocketException: Connection reset or Connect reset by peer:Socket write error

This exception may occur on both the client side and the server side. There are two reasons for this exception. The first is that if the Socket on one end is closed (or actively closed or closed due to abnormal exit), the other end still sends data, the first packet sent raises this exception (Connect reset by peer). The other is that one end exits, but the connection is not closed when exiting, and the other end throws this exception (Connection reset) if it is reading data from the connection. Simply put, it is caused by read and write operations after the connection is disconnected.

There is also a situation, if one end sends RST packets to interrupt the TCP connection, the other end will also have this exception. If it is tomcat, the exception is as follows:

org.apache.catalina.connector.ClientAbortException: java.io.IOException: Connection reset by peer

In order to improve performance, Ali's tcp health check eliminates hand-waving interaction and directly sends an RST to terminate the connection, which will cause this exception on the server side.
For the server, the general reasons can be considered as follows:

  • The number of concurrent connections of the server exceeds its capacity, and the server will actively Down some of the connections.

  • In the process of data transmission, the browser or the receiving client is closed, and the server is still sending data to the client.

java.net.SocketException: Broken pipe

This exception can occur on both client and server. After throwing SocketException: Connect reset by peer: Socket write error, this exception will be thrown if you continue to write data. The solution to the first two exceptions is to first ensure that all network connections are closed before the program exits, and secondly, to detect the other party's close connection operation, and to close the connection when the other party closes the connection.

For the exceptions in both cases 4 and 5, special attention should be paid to the maintenance of the connection. In the case of short connections, it is fine. If it is in the case of long connections, if the connection status is not properly maintained, it is very prone to abnormalities. Basically all you need to do for long connections is:

  • Detect the active disconnection of the other party (the other party calls the close method of Socket). Because the other party actively disconnects, if the other party is performing a read operation, the return value at this time is -1. Therefore, once it is detected that the other party is disconnected, it will actively close its own connection (call the close method of Socket).

  • To detect the other party's downtime, abnormal exit and network failure, the general practice is heartbeat detection. Both parties periodically send data to the other party, and also receive "heartbeat data" from the other party. If the other party does not receive the other party's heartbeat for several consecutive cycles, it can be judged that the other party is either down or abnormally exited or the network is blocked. Close the own connection; if it is the client, it can re-initiate the connection after a certain delay. Although Socket has a keep alive option to maintain the connection, if this option is used, it usually takes two hours to find out the other party's downtime, abnormal exit and network failure.

java.net.SocketException: Too many open files

Reason: The maximum number of handles to open files in the operating system is limited, which often occurs when many concurrent users access the server. Because in order to execute each user's application server to load a lot of files (a new socket needs a file handle), this will lead to a lack of open file handles.
Solution:

  • Try to type the class into a jar package, because a jar package only consumes one file handle. If it is not packaged, a class consumes one file handle.

  • The GC of java cannot close the file handle opened by the network connection. If close() is not executed, the file handle will always exist and cannot be closed.
    You can also consider setting the maximum number of open sockets to control this problem. Make relevant settings for the operating system and increase the maximum number of file handles.
    ulimit -aYou can view the current resource limit of ulimit -n 10240the system, and you can modify it. This modification is only valid for the current window.

Cannot assign requested address


    1. The port number is occupied and the address cannot be bound:
      java.net.BindException: Cannot assign requested address: bind: It is caused by the change of the IP address;

    2. The server network configuration is abnormal:
      /etc/hoststhe address configured in is wrong;

    3. There is also a situation where there is no loop address when ipconfig is executed, because the loop address configuration file is lost;

Status of the current tcpip connection

netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'

View keepalive parameters

sysctl -a |grep keepalive

$ netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'
LAST_ACK 4
CLOSE_WAIT 11
ESTABLISHED 21
TIME_WAIT 33
$ sysctl -a |grep keepalive'
net.ipv4.tcp_keepalive_intvl=75
net.ipv4.tcp_keepalive_probes=9
net.ipv4.tcp_keepalive_time=7200


Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

order lipitor 40mg & lt;a href="https://lipiws.top/"& gt;buy atorvastatin 10mg pill& lt;/a& gt; buy generic atorvastatin 80mg

Lqhqrq

2024-03-09

Leave a Reply

+