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

被折叠的 条评论
为什么被折叠?



