Explorar o código

添加redis分布式锁

linfutong %!s(int64=2) %!d(string=hai) anos
pai
achega
7b362db9ca

+ 20 - 0
zd-common/common-core/src/main/java/com/zd/common/core/redis/RedisService.java

@@ -150,4 +150,24 @@ public interface RedisService {
      * @return 对象列表
      */
     public Collection<String> keys(final String pattern);
+
+    /**
+     * 加锁
+     * @param key
+     * @param second
+     */
+    boolean lock(String key, long second);
+
+    /**
+     * 解除
+     * @param key
+     * @return
+     */
+    boolean unLock(String key);
+
+    /**
+     * 是否存在锁
+     * @param key
+     */
+    boolean isExistLock(String key);
 }

+ 20 - 0
zd-common/common-core/src/main/java/com/zd/common/core/redis/RedisServiceImpl.java

@@ -1,5 +1,6 @@
 package com.zd.common.core.redis;
 
+import com.zd.model.constant.BaseConstants;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.BoundSetOperations;
 import org.springframework.data.redis.core.HashOperations;
@@ -128,4 +129,23 @@ public class RedisServiceImpl implements RedisService {
     public Collection<String> keys(final String pattern) {
         return redisTemplate.keys(pattern);
     }
+
+    @Override
+    public boolean lock(String key, long second) {
+        return redisTemplate.opsForValue().setIfAbsent(BaseConstants.REDIS_LOCK + key, key, second, TimeUnit.SECONDS);
+    }
+
+    @Override
+    public boolean unLock(String key) {
+        return redisTemplate.delete(BaseConstants.REDIS_LOCK + key);
+    }
+
+    @Override
+    public boolean isExistLock(String key) {
+        Object obj = redisTemplate.opsForValue().get(BaseConstants.REDIS_LOCK + key);
+        if (obj != null) {
+            return Boolean.TRUE;
+        }
+        return Boolean.FALSE;
+    }
 }

+ 5 - 0
zd-model/src/main/java/com/zd/model/constant/BaseConstants.java

@@ -186,4 +186,9 @@ public interface BaseConstants {
 
 
     String DELAY_QUEUE = "delayQueue";
+
+    /**
+     * Redis前缀,需统一
+     */
+    String REDIS_LOCK = "redis_lock:";
 }

+ 50 - 43
zd-modules/zd-algorithm/src/main/java/com/zd/alg/monitor/HardwareDeviceMonitor.java

@@ -52,57 +52,64 @@ public class HardwareDeviceMonitor {
 
     @Scheduled(cron = "0 */9 * * * ?")
     public void checkPowerUse() {
-        if (dingTalkNotice != null && dingTalkNotice) {
-            ResultData result = remoteLabHardwareService.statistics();
-            if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
-                String jsonStr = JSONObject.toJSONString(result.getData());
-                JSONObject json = JSONObject.parseObject(jsonStr);
-                Integer offline = json.getInteger("powerSupplyOffline");
-                log.info("【设备监听提醒】 继电器异常监控--掉线数量:" + offline);
-                if (offline != null && offline > 0) {
-                    //获取离线列表
-                    ResultData data = remoteLabHardwareService.list("SWITCH", "OFFLINE");
-                    log.info("【设备监听提醒】 继电器异常监控--获取异常列表:"+JSONObject.toJSONString(data));
-                    if (data != null && data.getCode() == HttpStatus.SUCCESS && data.getData() != null) {
-                        //log.info("【设备监听提醒】 异常设备列表信息:" + data.getData());
-                        String listStr = JSONObject.toJSONString(data.getData());
-                        List<Map<String, Object>> list = JSONObject.parseObject(listStr, List.class);
-                        if (list != null && list.size() > 0) {
-                            Map<String, String> map = new HashMap<>();
-                            for (Map m : list) {
-                                String code = (String) m.get("relayCode");
-                                if (!map.containsKey(code)) {
-                                    map.put(code, "---信息[名称:" +
-                                            "" + m.get("name") + ",所在学院:" + m.get("deptName") + ",所在实验室:" + m.get("subjectName") + "]\n");
-                                }
-                            }
-                            //封装消息
-                            if (!map.isEmpty()) {
-                                Set<String> code = map.keySet();
-                                StringBuffer buffer = new StringBuffer();
-                                buffer.append("系统接入继电器设备离线信息:\n");
-                                boolean isSend = Boolean.FALSE;
-                                for (String key : code) {
-                                    Integer num = redisService.getCacheObject(redisPrefix+key);
-                                    if (num != null && num > 2) {
-                                        buffer.append("继电器[" + key + "] " + map.get(key));
-                                        redisService.deleteObject(redisPrefix+key);
-                                        isSend = Boolean.TRUE;
-                                    } else {
-                                        int value = num == null ? 1:num+1;
-                                        redisService.setCacheObject(redisPrefix+key, value, expire, TimeUnit.MINUTES);
+        String lockKey = "electric-relay-monitor";
+        if (!redisService.isExistLock(lockKey)) {
+            //添加锁
+            redisService.lock(lockKey,180);
+            if (dingTalkNotice != null && dingTalkNotice) {
+                ResultData result = remoteLabHardwareService.statistics();
+                if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
+                    String jsonStr = JSONObject.toJSONString(result.getData());
+                    JSONObject json = JSONObject.parseObject(jsonStr);
+                    Integer offline = json.getInteger("powerSupplyOffline");
+                    log.info("【设备监听提醒】 继电器异常监控--掉线数量:" + offline);
+                    if (offline != null && offline > 0) {
+                        //获取离线列表
+                        ResultData data = remoteLabHardwareService.list("SWITCH", "OFFLINE");
+                        log.info("【设备监听提醒】 继电器异常监控--获取异常列表:" + JSONObject.toJSONString(data));
+                        if (data != null && data.getCode() == HttpStatus.SUCCESS && data.getData() != null) {
+                            //log.info("【设备监听提醒】 异常设备列表信息:" + data.getData());
+                            String listStr = JSONObject.toJSONString(data.getData());
+                            List<Map<String, Object>> list = JSONObject.parseObject(listStr, List.class);
+                            if (list != null && list.size() > 0) {
+                                Map<String, String> map = new HashMap<>();
+                                for (Map m : list) {
+                                    String code = (String) m.get("relayCode");
+                                    if (!map.containsKey(code)) {
+                                        map.put(code, "---信息[名称:" +
+                                                "" + m.get("name") + ",所在学院:" + m.get("deptName") + ",所在实验室:" + m.get("subjectName") + "]\n");
                                     }
                                 }
-                                //通知
-                                if (isSend) {
-                                    String resp = DingTalkAlert.sendAlert(buffer.toString());
-                                    log.info("【设备监听提醒】 继电器异常监控--钉钉通知响应:" + resp);
+                                //封装消息
+                                if (!map.isEmpty()) {
+                                    Set<String> code = map.keySet();
+                                    StringBuffer buffer = new StringBuffer();
+                                    buffer.append("系统接入继电器设备离线信息:\n");
+                                    boolean isSend = Boolean.FALSE;
+                                    for (String key : code) {
+                                        Integer num = redisService.getCacheObject(redisPrefix + key);
+                                        if (num != null && num > 2) {
+                                            buffer.append("继电器[" + key + "] " + map.get(key));
+                                            redisService.deleteObject(redisPrefix + key);
+                                            isSend = Boolean.TRUE;
+                                        } else {
+                                            int value = num == null ? 1 : num + 1;
+                                            redisService.setCacheObject(redisPrefix + key, value, expire, TimeUnit.MINUTES);
+                                        }
+                                    }
+                                    //通知
+                                    if (isSend) {
+                                        String resp = DingTalkAlert.sendAlert(buffer.toString());
+                                        log.info("【设备监听提醒】 继电器异常监控--钉钉通知响应:" + resp);
+                                    }
                                 }
                             }
                         }
                     }
                 }
             }
+            //释放锁
+            redisService.unLock(lockKey);
         }
     }
 }