Home > Database > Redis > redis disconnected and reconnected

redis disconnected and reconnected

Release: 2020-04-24 09:13:33
forward
3314 people have browsed it

redis disconnected and reconnected

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){

            }

        }
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template