一、异常描述
通过客户端jedis连接redis服务器报出“redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Connection reset...Caused by: java.net.SocketException: Connection reset..”异常,详情见日志如下
redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Connection reset@b@ at redis.clients.jedis.Protocol.process(Protocol.java:146)@b@ at redis.clients.jedis.Protocol.read(Protocol.java:202)@b@ at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:285)@b@ at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:184)@b@ at redis.clients.jedis.BinaryJedis.save(BinaryJedis.java:2857)@b@ at com.xwood.publisher.util.JedisUtil.set(JedisUtil.java:31)@b@ at com.xwood.publisher.master.PublishEntityDataHandler.pushRemoteRedis(PublishEntityDataHandler.java:43)@b@ at com.xwood.publisher.master.PublishEntityDataHandler.run(PublishEntityDataHandler.java:36)@b@ at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)@b@ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)@b@ at java.util.concurrent.FutureTask.run(FutureTask.java:138)@b@ at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)@b@ at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)@b@ at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)@b@ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)@b@ at java.lang.Thread.run(Thread.java:662)@b@Caused by: java.net.SocketException: Connection reset@b@ at java.net.SocketInputStream.read(SocketInputStream.java:168)@b@ at java.net.SocketInputStream.read(SocketInputStream.java:90)@b@ at redis.clients.util.RedisInputStream.fill(RedisInputStream.java:109)@b@ at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:45)@b@ at redis.clients.jedis.Protocol.process(Protocol.java:131)@b@ ... 15 more
二、解决方法
原以为是因为redis服务端配置连接数及相关性能参数配置的问题,结果发现是代码问题(redis连接数并发没有上限,依赖当前系统打开最大文件句柄数),具体如下
public class JedisUtil{@b@ @b@ ...@b@ @b@ public static Jedis getclient(){@b@ return new Jedis(j_ip,j_port,60000);@b@ }@b@ @b@ public static void setcache(String key,String value){@b@ JedisUtil.getclient().set(key, value);@b@ }@b@ @b@ ...@b@}
这样导致每次setcache缓存都必须通过getclient()方法新建一个连接客户端,在并发多线程场景下造成了创建无数个redis连接客户端,因改为如下(单例模式)
public class JedisUtil{@b@ @b@ ...@b@ private static Jedis client = new Jedis(j_ip,j_port,60000);@b@ @b@ public static Jedis getclient(){@b@ return client;@b@ }@b@ ...@b@}