问题:定时任务在只部署一台服务器时没有问题,当需要集群时,就会重复执行多次。
解决方案: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 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 }
希望能帮助到大家,谢谢!