分散式定時任務重複執行解決方案--redis篇
阿新 • • 發佈:2020-08-19
問題:定時任務在只部署一臺伺服器時沒有問題,當需要叢集時,就會重複執行多次。
解決方案: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 */ 3031 String keyName() default ""; 32 }
核心程式碼實現:
1 package com.demo.aop; 2 import lombok.extern.slf4j.Slf4j; 3 import org.apache.commons.lang.StringUtils; 4 import org.aspectj.lang.ProceedingJoinPoint; 5 import org.aspectj.lang.annotation.Around; 6 import org.aspectj.lang.annotation.Aspect; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.data.redis.core.RedisTemplate; 9 import org.springframework.stereotype.Component; 10 import org.springframework.util.Assert; 11 12 import java.lang.reflect.Method; 13 import java.net.InetAddress; 14 import java.net.UnknownHostException; 15 import java.util.concurrent.TimeUnit; 16 17 /** 18 * @author shuangping.yang 19 */ 20 @Slf4j 21 @Aspect 22 @Component 23 public class RedisTryLockAspect { 24 25 @Autowired 26 private RedisTemplate redisTemplate; 27 28 InetAddress addr = null; 29 30 31 @Around("execution(* *.*(..)) && @annotation(com.demp.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 50 //獲取本機ip 51 try { 52 addr = InetAddress.getLocalHost(); 53 } catch (UnknownHostException e) { 54 log.error("獲取IP失敗--》", e); 55 } 56 String ip = addr.getHostAddress(); 57 // 設定redis key值 58 defKey = StringUtils.isBlank(keyName) ? defKey + aClass.getDeclaringClass() + method.getName() : defKey + keyName; 59 //根據redis 鎖的原理判斷是否執行成功,設值成功說明其他伺服器沒有執行定時任務,反則正在執行 60 if (redisTemplate.opsForValue().setIfAbsent(defKey, ip)) { 61 redisTemplate.expire(defKey, expireTime, TimeUnit.SECONDS); 62 log.info("獲得分散式鎖成功! key:{}", defKey); 63 pjp.proceed(); 64 redisTemplate.delete(defKey); 65 log.info("定時任務執行完,釋放分散式鎖成功,key:{}", defKey); 66 return; 67 } 68 Object redisVal = redisTemplate.opsForValue().get(defKey); 69 log.info("{}已在{}機器上佔用分散式鎖,聚類任務正在執行", defKey, redisVal); 70 } catch (NoSuchMethodException e) { 71 e.printStackTrace(); 72 log.error("Facet aop failed error {}", e.getLocalizedMessage()); 73 } catch (Throwable throwable) { 74 throwable.printStackTrace(); 75 } 76 } 77 }
使用示例:
1 @Scheduled(cron = "0 0 0/1 * * ?") 2 @RedisTryLock(keyName = "repeat_flow_direction_file_task", expireTime = 180) 3 public void redisTask() { 4 //業務程式碼實現 5 }
希望能幫助到大家,謝謝!