kongdeqiang
2022-12-16 daf6a95086087ec99232eea8b4648b7541881f7c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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;
        }
    }
 
 
}