The application must be able to self-recover after Redis is restarted, the network is interrupted and returns to normal. The following uses the jedis client in Java language as an example:
1 , as a publisher
The Jedis object cannot be used as a singleton, and the Jedis object cannot self-recover after the network is interrupted. Every time you publish a message, you should get the Jedis object from the JedisPool and then call the set method.
2. As a subscriber
When the network is interrupted, the psubscribe() method will no longer block and throw an exception, so you can use a while loop to handle the exception inside the loop. The code is as follows:
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){ } }
For more redis knowledge, please pay attention to the redis introductory tutorial column.
The above is the detailed content of redis disconnected and reconnected. For more information, please follow other related articles on the PHP Chinese website!