From 9b763080c80a321b1c081a38f93ed18c67556d7c Mon Sep 17 00:00:00 2001 From: skyjiang <470623352@qq.com> Date: Wed, 28 Feb 2024 09:54:23 +0800 Subject: [PATCH] enrich the information returned by toString() of Connection --- .../java/redis/clients/jedis/Connection.java | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index 50243e20d7e..f2604b6b0b6 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -5,6 +5,7 @@ import java.io.Closeable; import java.io.IOException; import java.net.Socket; +import java.net.SocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.CharBuffer; @@ -37,6 +38,8 @@ public class Connection implements Closeable { private int soTimeout = 0; private int infiniteSoTimeout = 0; private boolean broken = false; + private boolean strValActive; + private String strVal; public Connection() { this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); @@ -69,7 +72,42 @@ public Connection(final JedisSocketFactory socketFactory, JedisClientConfig clie @Override public String toString() { - return "Connection{" + socketFactory + "}"; + if (strValActive == broken && strVal != null) { + return strVal; + } + + int id = hashCode(); + SocketAddress remoteAddr = socket.getRemoteSocketAddress(); + SocketAddress localAddr = socket.getLocalSocketAddress(); + if (remoteAddr != null) { + StringBuilder buf = new StringBuilder(96) + .append("[id: 0x") + .append(id) + .append(", L:") + .append(localAddr) + .append(broken? " ! " : " - ") + .append("R:") + .append(remoteAddr) + .append(']'); + strVal = buf.toString(); + } else if (localAddr != null) { + StringBuilder buf = new StringBuilder(64) + .append("[id: 0x") + .append(id) + .append(", L:") + .append(localAddr) + .append(']'); + strVal = buf.toString(); + } else { + StringBuilder buf = new StringBuilder(16) + .append("[id: 0x") + .append(id) + .append(']'); + strVal = buf.toString(); + } + + strValActive = broken; + return strVal; } public final RedisProtocol getRedisProtocol() {