package com.wgcloud.util;
|
|
import com.wgcloud.entity.DbInfo;
|
import com.wgcloud.service.DbInfoService;
|
import com.wgcloud.service.LogInfoService;
|
import com.wgcloud.util.msg.WarnMailUtil;
|
import com.wgcloud.util.msg.WarnPools;
|
import com.wgcloud.util.staticvar.StaticKeys;
|
import org.apache.commons.lang3.StringUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.stereotype.Component;
|
import redis.clients.jedis.Jedis;
|
|
import javax.annotation.Resource;
|
|
/**
|
* @version v3.3
|
* @ClassName: RedisUtil
|
* @author: http://www.wgstart.com
|
* @date: 2022年11月10日
|
* @Description: Redis工具类
|
* @Copyright: 2019-2022 wgcloud. All rights reserved.
|
*/
|
@Component
|
public class RedisUtil {
|
|
private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
|
|
@Resource
|
private LogInfoService logInfoService;
|
@Resource
|
private DbInfoService dbInfoService;
|
|
|
/**
|
* 连接redis,返回空说明失败
|
* 返回PONG说明成功
|
*
|
* @param dbInfo
|
* @return
|
*/
|
public String connectRedis(DbInfo dbInfo) throws Exception {
|
try {
|
dbInfo.setDbState(StaticKeys.ON_STATE);
|
//连接redis时候,dbUrl存贮redis服务器IP,userName存贮的是redis端口
|
//连接指定的redis
|
Jedis jedis = new Jedis(dbInfo.getDbUrl(), Integer.valueOf(dbInfo.getUserName()), 10000);
|
//如果有密码则需要下面这一行
|
if (!StringUtils.isEmpty(dbInfo.getPasswd())) {
|
jedis.auth(dbInfo.getPasswd());
|
}
|
//查看服务是否运行,运行正常的话返回一个字符串PONG,否则返回一个连接错误
|
String pong = jedis.ping();
|
logger.info("connectRedis-------" + pong);
|
jedis.close();
|
if (null != WarnPools.MEM_WARN_MAP && null != WarnPools.MEM_WARN_MAP.get(dbInfo.getId())) {
|
Runnable runnable = () -> {
|
WarnMailUtil.sendDbDown(dbInfo, false);
|
};
|
ThreadPoolUtil.executor.execute(runnable);
|
}
|
//只有数据源在线时候,才更新时间,连接失败就不更新时间
|
dbInfo.setCreateTime(DateUtil.getNowTime());
|
dbInfoService.updateById(dbInfo);
|
return pong;
|
} catch (Exception e) {
|
dbInfo.setDbState(StaticKeys.DOWN_STATE);
|
logger.error("连接redis错误", e);
|
logInfoService.save("连接redis错误:" + dbInfo.getAliasName(), "数据库别名:" + dbInfo.getAliasName() + "," + e.toString(), StaticKeys.LOG_XTCZ);
|
dbInfoService.updateById(dbInfo);
|
Runnable runnable = () -> {
|
WarnMailUtil.sendDbDown(dbInfo, true);
|
};
|
ThreadPoolUtil.executor.execute(runnable);
|
return null;
|
}
|
}
|
|
|
}
|