Skip to content

Commit

Permalink
Fixed the problem of abnormal socket status during DNS resolution (#2849
Browse files Browse the repository at this point in the history
)

* Fixed the problem of abnormal socket status during DNS resolution

fix #2848

* Apply suggestions from code review

Co-authored-by: M Sazzadul Hoque <7600764+sazzad16@users.noreply.github.com>

Co-authored-by: M Sazzadul Hoque <7600764+sazzad16@users.noreply.github.com>
  • Loading branch information
yangbodong22011 and sazzad16 committed Jan 31, 2022
1 parent 1a451e4 commit 3f60dcb
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,24 @@ public DefaultJedisSocketFactory(HostAndPort hostAndPort, JedisClientConfig conf
}
}

private void connectToFirstSuccsefulHost(Socket socket, HostAndPort hostAndPort) throws Exception {
private Socket connectToFirstSuccsefulHost(HostAndPort hostAndPort) throws Exception {
List<InetAddress> hosts = Arrays.asList(InetAddress.getAllByName(hostAndPort.getHost()));
if (hosts.size() > 1) {
Collections.shuffle(hosts);
}

JedisConnectionException jce = new JedisConnectionException("Failed to connect to any host resolved for DNS name.");
for (InetAddress host : hosts) {
try {
Socket socket = new Socket();

socket.setReuseAddress(true);
socket.setKeepAlive(true); // Will monitor the TCP connection is valid
socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method, the underlying socket is closed immediately

socket.connect(new InetSocketAddress(host.getHostAddress(), hostAndPort.getPort()), connectionTimeout);
return;
return socket;
} catch (Exception e) {
jce.addSuppressed(e);
}
Expand All @@ -75,14 +83,8 @@ private void connectToFirstSuccsefulHost(Socket socket, HostAndPort hostAndPort)
public Socket createSocket() throws JedisConnectionException {
Socket socket = null;
try {
socket = new Socket();
socket.setReuseAddress(true);
socket.setKeepAlive(true); // Will monitor the TCP connection is valid
socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method, the underlying socket is closed immediately

HostAndPort _hostAndPort = getSocketHostAndPort();
connectToFirstSuccsefulHost(socket, _hostAndPort);
socket = connectToFirstSuccsefulHost(_hostAndPort);
socket.setSoTimeout(socketTimeout);

if (ssl) {
Expand Down

0 comments on commit 3f60dcb

Please sign in to comment.