redis 断线重连接

该博客介绍了一个使用多线程实现的Redis断线重连接方案。通过创建`RedisUtils`类并实现`Runnable`接口,当Redis连接断开时,线程会不断尝试重新连接,直到连接成功。在业务代码中,通过`RedisUtils.RedisState`标志判断Redis状态,并在异常时关闭连接,确保系统的稳定运行。

使用多线程做到断线重连接

图形参考tomcat接受请求,处理http头模型

code:

public class RedisUtils implements Runnable {

    public static boolean RedisState = true;

    public static RedisUtils redisUtils = new RedisUtils();

    static{

       new Thread(redisUtils).start();

    }

 

    @Override

    public void run() {

        while (true) {

            synchronized (redisUtils) {

                while (!RedisState) {

                   try {

                       Jedis jedis = new Jedis("10.0.0.4");

                       jedis.auth("xiaoxiao");

                       String ping = jedis.ping();

                       if (ping.equals("PONG")) {

                           RedisState = true;

                           System.out.println("redis连接成功,停止当前线程");

                           synchronized (redisUtils){

                               redisUtils.wait();

                           }

                       }

                   }catch (Exception e){

                       System.out.println("redis连接失败 10s继续尝试连接");

                       try {

                           Thread.sleep(10000);

                       } catch (InterruptedException e1) {

                           e1.printStackTrace();

                       }

                   }

 

                }

                try {

                    redisUtils.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        }

    }

 

}

Code:

String cache_name = cache.value();

    Object resule = null;

    if (RedisUtils.RedisState) {

        try {

            Object caches = redisTemplate.opsForHash().get(cache_name, joinPoint.getArgs()[0]);

            System.out.println(caches);

            if (caches != null) {

                logger.info("Redis 取值");

                return caches;

            }

        } catch (Exception e) {

            logger.error(e.toString());

            RedisUtils.RedisState = false;

            synchronized (RedisUtils.redisUtils) {

                RedisUtils.redisUtils.notify();

            }

        }

    }

    try {

 

        resule = joinPoint.proceed();

        logger.info("数据库取值");

        if (RedisUtils.RedisState) {

            redisTemplate.opsForHash().put(cache_name, joinPoint.getArgs()[0], resule);

        }

    } catch (Throwable throwable) {

        throwable.printStackTrace();

    }

    return resule;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值