public class ReStartTestRedis extends PoolConfig{
private static int failGetPoolResourceCount = 0;//累计连接失败的次数
private static final String start = "start.bat";
private static final String stop = "stop.bat";
public static void main(String[] args) throws ParseException, IOException, InterruptedException {
reStart();
}
public static void reStart() throws ParseException, IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq " + "redis-server-master.exe" + "\"");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
//监测操作系统中进程redis-server-master.exe是否存在
boolean processExistsFlag = false;
while ((line = bufferedReader.readLine()) != null) {
//if (line.contains("redis-server-master.exe")) {
if (line.contains("redis-server.exe")) {
processExistsFlag = true;
}
}
if(!processExistsFlag){
Runtime.getRuntime().exec(System.getProperty("user.dir")+"/bin/"+start);
Thread.sleep(5000l);
logger.info("redis 6379已经重启");
}
Jedis j = null;
try {
j = PoolConfig.pool.getResource();
PoolConfig.pool.returnResource(j);
} catch (JedisConnectionException e) {
e.printStackTrace();
failGetPoolResourceCount++;
logger.info("redis 6379系统进程[redis-server-master.exe]正常运行,却不能从连接池中取得Jedis连接对象,发生次数:"+failGetPoolResourceCount+"次");
//超过五次都不能取得连接对象Jedis则强制重启redis-server
if(failGetPoolResourceCount > 5){
try {
//发现redis-server-master.exe进程没停止,但无法从连接池中取得Jedis对象,将redis-server-master.exe强制停止
Runtime.getRuntime().exec(stop);
logger.info("redis 6379已经停机");
//启动
Runtime.getRuntime().exec(start);
Thread.sleep(5000l);
//测试是否已经启动且恢复数据
// j = PoolConfig.pool.getResource();
// Set<String> set = j.keys("*");
// System.out.println(set.size());
logger.info("redis 6379已经重启");
failGetPoolResourceCount = 0;
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
} catch(Exception e1){
e1.printStackTrace();
}finally{
}
}
}
}
}
start.bat
cd E:/work/redis-server/redis-2.4.5-win64
e:
start redis-server.exe
stop.bat
cd E:\work\redis-server\redis-2.4.5-win64
e:
taskkill /f /im redis-server.exe