linux 定时任务pjp,分布式定时任务重复执行解决方案--redis篇

这里将告诉您分布式定时任务重复执行解决方案--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 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 }

希望能帮助到大家,谢谢!

分布式定时任务重复执行解决方案--redis篇就为您介绍到这里,感谢您关注懒咪学编程c.lanmit.com.

本文地址:https://c.lanmit.com/bianchengkaifa/Java/104913.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值