分布式定時任務重復執行解決方案--redis篇


問題:定時任務在只部署一台服務器時沒有問題,當需要集群時,就會重復執行多次。

解決方案:1. 利用數據庫樂觀鎖;2. 基於Redis的分布式鎖;3. 基於ZooKeeper的分布式鎖。

這里我使用的是redis分布鎖的方式實現,自己封裝了一個注解,如有問題請聯系我一下,謝謝!

加鎖 :同一個定時任務同時多次給redis加鎖(key),如果存在key,則加鎖失敗,如果不存在,則嘗試去加鎖,返回加鎖結果。 

解鎖: 設置一下過期時間為20秒(可根據任務執行長短調整),過期后自動釋放掉,當定時任務執行完后redis還沒有過期是就手動解鎖。

封裝aop注解:

 1 package com.demo.aop;
 2 
 3  4 import java.lang.annotation.*;
 5 
 6 /**
 7  * ************************************************
 8  * 功能描述:   TODO
 9  *
10  * @author shuangping.yang
11  * @version 1.0
12  * @ClassName RedisTryLock
13  * @date 2020.07.15 下午 03:53 創建文件
14  * @see ************************************************
15  */
16 @Target(ElementType.METHOD)
17 @Retention(RetentionPolicy.RUNTIME)
18 @Documented
19 public @interface RedisTryLock {
20     /**
21      * 鎖的有效時間長,單位:秒
22      *
23      * @return
24      */
25     int expireTime() default 10;
26 
27     /**
28      * 自定義鎖的keyName(不用包含namespace,內部已實現)
29      */
30 31     String keyName() default "";
32 }

 

核心代碼實現:

 1 package com.demo.aop;
 2 
 3 import lombok.extern.slf4j.Slf4j;
 4 import org.apache.commons.lang.StringUtils;
 5 import org.aspectj.lang.ProceedingJoinPoint;
 6 import org.aspectj.lang.annotation.Around;
 7 import org.aspectj.lang.annotation.Aspect;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.data.redis.core.RedisTemplate;
10 import org.springframework.stereotype.Component;
11 import org.springframework.util.Assert;
12 
13 import java.lang.reflect.Method;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.concurrent.TimeUnit;
17 
18 /**
19  * @author shuangping.yang
20  */
21 @Slf4j
22 @Aspect
23 @Component
24 public class RedisTryLockAspect {
25 
26     @Autowired
27     private RedisTemplate<String, String> redisTemplate;
28     InetAddress addr = null;
29 
30 
31     @Around("execution(* *.*(..)) && @annotation(com.demo.aop.RedisTryLock)")
32     public void redisTryLockPoint(ProceedingJoinPoint pjp) throws Exception {
33         String defKey = "redis:lock:";
34         RedisTryLock annotation = null;
35         Method method = null;
36         //獲得所在切點的該類的class對象
37         Class aClass = pjp.getTarget().getClass();
38         //獲取該切點所在方法的名稱,每一個使用切面的方法
39         String name = pjp.getSignature().getName();
40         try {
41             //通過反射獲得該方法
42             method = aClass.getMethod(name);
43             //獲得該注解
44             annotation = method.getAnnotation(RedisTryLock.class);
45             //獲取注解對應的值keyName,expireTime
46             String keyName = annotation.keyName();
47             Integer expireTime = annotation.expireTime();
48             Assert.isTrue(0 != expireTime, "redis lock's expireTime is null");
49             //獲取本機ip
50             try {
51                 addr = InetAddress.getLocalHost();
52 
53             } catch (UnknownHostException e) {
54                 log.error("獲取IP失敗--》", e);
55 
56             }
57             String ip = addr.getHostAddress();
58             // 設置redis key值
59 
60             defKey = StringUtils.isBlank(keyName) ? defKey + aClass.getDeclaringClass() + method.getName() : defKey + keyName;
61             //根據redis 鎖的原理判斷是否執行成功,設值成功說明其他服務器沒有執行定時任務,反則正在執行
62             if (redisTemplate.opsForValue().setIfAbsent(defKey, ip)) {
63                 redisTemplate.expire(defKey, expireTime, TimeUnit.SECONDS);
64                 log.info("獲得分布式鎖成功! key:{}", defKey);
65                 pjp.proceed();
66                 redisTemplate.delete(defKey);
67                 log.info("定時任務執行完,釋放分布式鎖成功,key:{}", defKey);
68                 return;
69 
70             }
71             Object redisVal = redisTemplate.opsForValue().get(defKey);
72             log.info("{}已在{}機器上占用分布式鎖,聚類任務正在執行", defKey, redisVal);
73 
74         } catch (NoSuchMethodException e) {
75             e.printStackTrace();
76             log.error("Facet aop failed error {}", e.getLocalizedMessage());
77 
78         } catch (Throwable throwable) {
79             throwable.printStackTrace();
80 
81         }
82 
83     }
84 }

 

 

使用示例:

1     @Scheduled(cron = "0 0 0/1 * * ?")
2     @RedisTryLock(keyName = "repeat_flow_direction_file_task", expireTime = 180)
3     public void redisTask() {
4         //業務代碼實現
5     }

希望能幫助到大家,謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM