记一次多线程时获取redis连接失败

先上问题:

redis.clients.jedis.exceptions.JedisConnectionException: Attempting to read from a broken connection
	at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:274)
	at redis.clients.jedis.Connection.getIntegerReply(Connection.java:220)
	at redis.clients.jedis.Jedis.exists(Jedis.java:213)
	at com.cmcc.message.util.JedisUtil.existKey(JedisUtil.java:138)
	at com.cmcc.message.util.TokenUtil.getTokenConfig(TokenUtil.java:35)
	at com.cmcc.message.consumer.SmsConsumer.process(SmsConsumer.java:68)
	at com.cmcc.message.consumer.SmsConsumer$$FastClassBySpringCGLIB$$8503f9d5.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
	at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)

jedis配置代码:

@Configuration
public class JedisClusterConfig {
    
    private static RedisProperties redisProperties;
    
    private static Jedis jedisCluster = null;
    
    @Autowired
    private RedisProperties redisProperties2;
 
    @PostConstruct
    public void init() {
        redisProperties = redisProperties2;
        if (jedisCluster==null) {
            try {
                jedisCluster = reloadJedisCluster();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取JedisCluster对象
     * 
     * @return
     * @throws Exception
     */
    public static Jedis getCluster() throws Exception {
        if (jedisCluster == null) {
            synchronized (JedisClusterConfig.class) {
                jedisCluster = reloadJedisCluster();
            }
            return jedisCluster;
        } else {
            return jedisCluster;
        }
    }
    
//    public static JedisCluster getJedisCluster(){
//        String [] serverArray=redisProperties.getClusterNodes().split(",");
//        Set<HostAndPort> nodes=new HashSet<>();
//
//        for (String ipPort:serverArray){
//            String [] ipPortPair=ipPort.split(":");
//            nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim())));
//
//        }
//        String redisAuthPass = redisProperties.getRedisAuthPass();
//        return  new JedisCluster(nodes,2000, 2000, 6, redisAuthPass, new JedisPoolConfig());
//    }
    
    private static Jedis reloadJedisCluster() throws Exception {
        System.out.println("初始化实体");	
        Jedis cluster = null;
        String redisAuthPass = redisProperties.getRedisAuthPass();
        String addrs = redisProperties.getClusterNodes();
        String [] ipPortPair=addrs.split(":");
        HostAndPort node = new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim()));
        cluster = new Jedis(node);
        cluster.auth(redisAuthPass);
        return cluster;
    }

猜测原因:

多线程请求redis获取内容,线程数>2就会报这个错误,百度了一下这个问题,没找到很好的解答。

初步猜测是因为没有使用jedispool,又没有释放连接导致,尝试更新为jedispool。

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
 
    protected static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
 
    @Value("${spring.redis.host}")
    private String host;
 
    @Value("${spring.redis.port}")
    private int port;
 
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxTotal;
 
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
 
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;
 
    @Value("${spring.redis.password}")
    private String password;
 
    @Value("${spring.redis.timeout}")
    private int timeout;
 
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        JedisPool jedisPool = null;
        if(password == null || password.equals("")){
            jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
        }else{
            jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout,password);
        }
        logger.info("JedisPool注入成功!!");
        logger.info("redis地址:" + host + ":" + port);
        return jedisPool;
    }
}

经测试,报错没再出现。

后续又查看了jedisCluster的源码,发现jediscluster默认可以实现连接池。

遗留问题:

  1. jedis连接默认释放时间是多少?为什么并发情况下会出现这种异常
### 回答1: 编写Redis cluster连接池需要使用Java客户端,例如Jedis,Lettuce等,并使用连接池管理器来管理连接。具体的实现可以参考Redisson的源码,它是一个开源的Redis Java连接池库。 ### 回答2: RedisCluster是Redis的一个集群模式,它以分布式的方式存储数据,并提供高可用性和性能的读写操作。在使用Java连接RedisCluster,可以使用JedisCluster对象进行连接管理并操作Redis集群。 下面是一个简单的示例,展示如何使用Java编写一个RedisCluster连接池: 1. 首先,我们需要在pom.xml中添加Jedis依赖: ```xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.10.0</version> </dependency> ``` 2. 创建RedisCluster连接池对象。可以使用Apache Commons Pool来实现一个连接池,用于管理连接的复用和分配等操作: ```java import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashSet; import java.util.Set; public class RedisClusterConnectionPool { private static final String HOST = "127.0.0.1"; private static final int PORT = 6379; private static final int CONNECTION_TIMEOUT = 2000; private static final int MAX_TOTAL_CONNECTIONS = 10; private static final int MAX_IDLE_CONNECTIONS = 5; private static final int MIN_IDLE_CONNECTIONS = 1; private static final long MAX_WAIT_TIME = 2000; private JedisCluster jedisCluster; public RedisClusterConnectionPool() { Set<HostAndPort> jedisClusterNodes = new HashSet<>(); jedisClusterNodes.add(new HostAndPort(HOST, PORT)); // 配置连接池 GenericObjectPoolConfig<JedisCluster> poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(MAX_TOTAL_CONNECTIONS); poolConfig.setMaxIdle(MAX_IDLE_CONNECTIONS); poolConfig.setMinIdle(MIN_IDLE_CONNECTIONS); poolConfig.setMaxWaitMillis(MAX_WAIT_TIME); // 创建连接池 GenericObjectPool<JedisCluster> connectionPool = new GenericObjectPool<>(new RedisClusterConnectionFactory(jedisClusterNodes), poolConfig); // 从连接获取JedisCluster对象 try { jedisCluster = connectionPool.borrowObject(); } catch (Exception e) { e.printStackTrace(); } } } ``` 3. 创建RedisClusterConnectionFactory类,用于创建JedisCluster连接: ```java import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.Set; public class RedisClusterConnectionFactory implements PooledObjectFactory<JedisCluster> { private Set<HostAndPort> jedisClusterNodes; public RedisClusterConnectionFactory(Set<HostAndPort> jedisClusterNodes) { this.jedisClusterNodes = jedisClusterNodes; } @Override public PooledObject<JedisCluster> makeObject() throws Exception { return new DefaultPooledObject<>(new JedisCluster(jedisClusterNodes)); } @Override public void destroyObject(PooledObject<JedisCluster> p) throws Exception { p.getObject().close(); } @Override public boolean validateObject(PooledObject<JedisCluster> p) { return p.getObject().isConnected(); } @Override public void activateObject(PooledObject<JedisCluster> p) throws Exception { } @Override public void passivateObject(PooledObject<JedisCluster> p) throws Exception { } } ``` 以上就是一个使用Java编写的RedisCluster连接池的基本实现。通过这个连接池,我们可以方便地获取并管理RedisCluster的连接对象,以便进行各种读写操作。同连接池也提供了连接复用、性能优化等功能,提高了系统的可靠性和性能。 ### 回答3: Java RedisCluster连接池是一个用于管理Redis集群连接的工具,用于提高连接的复用性和性能。 首先,我们需要引入redis.clients.jedis.JedisCluster类作为Redis集群连接的核心类,并在项目中引入Jedis库。 接下来,我们可以创建一个RedisClusterPool类,该类包含以下几个主要方法: 1. 初始化连接池:在初始化方法中,我们可以通过配置文件或硬编码方式获取Redis集群的主机地址、端口号等信息,并创建一个连接池对象。在连接池对象中,我们可以设置最大连接数、最大空闲连接数、连接间等参数。 2. 获取连接:通过getConnection方法,我们可以从连接池中获取一个可用的Redis连接连接池管理多个连接对象,并根据需要进行创建、销毁和维护。 3. 释放连接:使用完Redis连接后,我们需要将连接释放回连接池,以供其他线程使用。通过releaseConnection方法,我们可以将连接归还到连接池中。 4. 关闭连接池:在程序结束,需要显式地关闭连接池,以释放连接池所占用的资源。通过closePool方法,我们可以关闭连接池,并释放所有连接。 此外,我们还可以增加一些辅助方法,用于检查连接是否可用、重连失败连接等。 使用Java编写RedisCluster连接池的好处是,可以有效地管理和复用Redis连接,提高系统性能和稳定性。同连接池可以减少重复创建和销毁连接的开销,并可以根据实际需求自动调整连接的创建和回收策略,提供更好的连接资源管理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值