redis断线重连

2020-08-05 10:32:47

应用在Redis重启、网络闪断并恢复正常后,应用必须能够自恢复,下面以Java语言的jedis客户端为例说明:

1、作为发布者

Jedis对象不能作为单例,网络闪断后该Jedis对象无法自恢复。应该每次发布消息时,从JedisPool中取Jedis对象,再调用set方法。

2、作为订阅者

当网络闪断后psubscribe()方法不再阻塞并抛出异常,所以可以使用while循环,在循环内部处理异常,代码如下:

while(true){            Jedis redis = this.jedisPool.getResource();            try{                redis.psubscribe(this, channelArray);            }catch(JedisConnectionException e){                logger.warn("Exception :", e);                logger.warn("Exit redis psubscribe, retry after 1 second");            }catch(Exception e){                logger.error("Exception:", e);            }            try{                Thread.sleep(1000);            }catch(Exception unused){            }            try{                if(redis != null){                    redis.close();                }            }catch(Exception unused){            }        }

更多redis知识请关注redis入门教程栏目。