java redis反复运行_分布式定时任务重复执行解决方案--redis篇

本文介绍了如何使用Java和Redis实现分布式锁,以防止分布式环境中的定时任务重复执行。通过在方法上添加自定义注解`RedisTryLock`,利用Redis的`setIfAbsent`操作尝试设置键值,如果成功则执行任务并删除锁,从而确保同一时间只有一个实例执行任务。
摘要由CSDN通过智能技术生成

1 packagecom.demo.aop;2

3 importlombok.extern.slf4j.Slf4j;4 importorg.apache.commons.lang.StringUtils;5 importorg.aspectj.lang.ProceedingJoinPoint;6 importorg.aspectj.lang.annotation.Around;7 importorg.aspectj.lang.annotation.Aspect;8 importorg.springframework.beans.factory.annotation.Autowired;9 importorg.springframework.data.redis.core.RedisTemplate;10 importorg.springframework.stereotype.Component;11 importorg.springframework.util.Assert;12

13 importjava.lang.reflect.Method;14 importjava.net.InetAddress;15 importjava.net.UnknownHostException;16 importjava.util.concurrent.TimeUnit;17

18 /**

19 *@authorshuangping.yang20 */

21 @Slf4j22 @Aspect23 @Component24 public classRedisTryLockAspect {25

26 @Autowired27 private RedisTemplateredisTemplate;28 InetAddress addr = null;29

30

31 @Around("execution(* *.*(..)) && @annotation(com.demo.aop.RedisTryLock)")32 public void redisTryLockPoint(ProceedingJoinPoint pjp) throwsException {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 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值