使用redis-cluster搭建Redis缓存集群,需要维护多个redis实例;
1.采用机器底层脚本,对进程进行监控,可由系统部门来处理;
2.采用程序进行生死监控,有开发来自由处理;
下面介绍使用java代码进行redis实例生死监控;
部署java程序,启动定时任务执行探测;对于每个实例的存活,定时任务会每隔n分钟,重试多次ping命令去检查它的存活性,如果多次都ping不通,则发送报警短信通知相关负责人,上线排查问题。
代码来自网络:
public boolean isRun(final String ip, final int port) {
boolean isRun = new IdempotentConfirmer() {
private int timeOutFactor = 1;
@Override
public boolean execute() {
Jedis jedis = new Jedis(ip, port);
try {
jedis.getClient().setConnectionTimeout(Protocol.DEFAULT_TIMEOUT * (timeOutFactor++));
jedis.getClient().setSoTimeout(Protocol.DEFAULT_TIMEOUT * (timeOutFactor++));
String pong = jedis.ping();
return pong != null && pong.equalsIgnoreCase("PONG");
} catch (JedisDataException e) {
String message = e.getMessage();
logger.warn(e.getMessage());
if (StringUtils.isNotBlank(message) && message.startsWith("LOADING")) {
return true;
}
return false;
} catch (Exception e) {
logger.warn("{}:{} error message is {} ", ip, port, e.getMessage());
return false;
} finally {
jedis.close();
}
}
}.run();
return isRun;
}
package com.sohu.cache.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 幂等操作器
*/
public abstract class IdempotentConfirmer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private int retry = 3;
protected IdempotentConfirmer(int retry) {
this.retry = retry;
}
public IdempotentConfirmer() {
}
public abstract boolean execute();
public boolean run() {
while (retry-- > 0) {
try {
boolean isOk = execute();
if (isOk){
return true;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
continue;
}
}
return false;
}
}