Spring Scheduled + Redis 实现分布式定时器(1)

本文介绍了一种利用Spring框架结合Redis实现的自定义定时任务方案。该方案通过自定义注解、反射机制以及Redis锁来确保任务的正确调度与执行。文章详细分解了实现过程中的关键技术点与代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:https://blog.csdn.net/wzs298/article/details/77608670

1、需要了解的技术点:
1.1、Redis的命令:SETNX,EXPIRE;
1.2、 Spring的Scheduled定时器注解,触发器,任务,调度器;
1.3、 Spring的applicationContext上下文对象,自定义注解,java反射机制;

2、思路:
2.1、创建一个自定义注解,参数:cron(时间格式);
2.2、创建一个@ Component组件,用来实现自定义注解的功能,
     2.2.1、实现 ApplicationContextAware 接口,用来获取spring的ApplicationContext上下文对象;     
     2.2.2、 实现 BeanPostProcessor接口,用来获取自定义注解所对应的方法;
     2 .2.3、实现 SchedulingConfigurer 接口,用来创建定时器任务;
     2.2.4、创建一个实现Runabel接口的类,用来反射自定义注解所对应的方法和抢占redis的锁;
     2.2.5、创建一个实现 Trigger接口的 触发器对象,用来获取下一次执行任务的时间,以便给redis设置锁的生存时间;
2.3、程序执行流程:
2.3.1、给需要加定时器的方法加上自定义注解
2.3.2、程序启动,获取spring上下文对象;
2.3.3、扫描自定义注解所对应的方法;
2.3.4、根据每个自定义注解的信息创建对应触发器和任务;
2.3.5、调度器触发任务时,先去抢占锁,再根据情况判断本实例是否要执行任务;

3、代码分解:
3.1、创建自定义注解;
[java]  view plain  copy
  1. @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Inherited  
  4. @Documented  
  5. public @interface KyScheduled {  
  6.     /** 
  7.      * A cron-like expression, extending the usual UN*X definition to include 
  8.      * triggers on the second as well as minute, hour, day of month, month 
  9.      * and day of week.  e.g. {@code "0 * * * * MON-FRI"} means once per minute on 
  10.      * weekdays (at the top of the minute - the 0th second). 
  11.      * @return an expression that can be parsed to a cron schedule 
  12.      */  
  13.     String cron() default "";  
  14. }  
3.2、创建KyTask类,用来记录自定义注解的信息和注解对应方法的信息;
[java]  view plain  copy
  1. public class KyScheduledExecution {  
  2. public class KyTask {  
  3.         private KyScheduled kyScheduled;  
  4.         private Method kyMethod;  
  5.         public KyScheduled getKyScheduled() {  
  6.             return kyScheduled;  
  7.         }  
  8.         public void setKyScheduled(KyScheduled kyScheduled) {  
  9.             this.kyScheduled = kyScheduled;  
  10.         }  
  11.         public Method getKyMethod() {  
  12.             return kyMethod;  
  13.         }  
  14.         public void setKyMethod(Method kyMethod) {  
  15.             this.kyMethod = kyMethod;  
  16.         }  
  17.     }  
  18. }  
3.3、实现 ApplicationContextAware接口,获取spring上下文对象;
原因:如果单纯使用java的反射机制,当定时器任务使用 @Autowired 注解时,会获取不到bean实例,所以要实现 ApplicationContextAware接口
[java]  view plain  copy
  1. @Component  
  2. public class KyScheduledExecution implements ApplicationContextAware {  
  3.     private ApplicationContext applicationContext;  
  4.     @Override  
  5.     public void setApplicationContext(ApplicationContext context) throws BeansException {  
  6.         this.applicationContext = context;  
  7.     }  
  8.     private Object getBean(Class classname) {  
  9.         try {  
  10.             return this.applicationContext.getBean(classname);  
  11.         } catch (Exception e) {  
  12.             log.error(e);  
  13.             return "";  
  14.         }  
  15.     }  
  16. }  
3.4、实现BeanPostProcessor接口,获取自定义注解信息;
[java]  view plain  copy
  1. @Component  
  2. public class KyScheduledExecution implements BeanPostProcessor {  
  3.     private Log log = LogFactory.getLog(getClass());  
  4.     //记录任务集合  
  5.     private List<KyTask> kyTaskList = new ArrayList<>();  
  6.     @Override  
  7.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  8.         return bean;  
  9.     }  
  10.     /** 
  11.      * 获取所有自定义注解,并记录注解和方法的信息 
  12.      * @param bean     bean 
  13.      * @param beanName beanName 
  14.      * @return Object 
  15.      * @throws BeansException BeansException 
  16.      */  
  17.     @Override  
  18.     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {  
  19.         Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());  
  20.         if (methods != null) {  
  21.             for (Method method : methods) {  
  22.                 KyScheduled annotation = AnnotationUtils.findAnnotation(method, KyScheduled.class);  
  23.                 if (annotation != null && !"".equals(annotation.cron())) {  
  24.                     KyTask at = new KyTask();  
  25.                     at.setKyScheduled(annotation);  
  26.                     at.setKyMethod(method);  
  27.                     kyTaskList.add(at);  
  28.                 }  
  29.             }  
  30.         }  
  31.         return bean;  
  32.     }  
  33. }  
3.5、在 KyScheduledExecution   在类中引入redis客户端,并实现获取redis锁的方法, 需要在3.3的 setApplicationContext方法中执行 createRedisClient()
[java]  view plain  copy
  1. public class KyScheduledExecution{  
  2.     private Log log = LogFactory.getLog(getClass());  
  3.     @Value("${spring.redis.host}")  
  4.     private String redisHost;  
  5.     @Value("${spring.redis.port}")  
  6.     private int redisPort;  
  7.     private Jedis jedis;  
  8.     //记录任务集合  
  9.     private List<KyTask> kyTaskList = new ArrayList<>();  
  10.     private ApplicationContext applicationContext;  
  11.     /** 
  12.      * 创建redis客户端 
  13.      */  
  14.     private void createRedisClient() {  
  15.         if (jedis == null) {  
  16.             jedis = new Jedis(redisHost, redisPort);  
  17.         }  
  18.     }  
  19.     /** 
  20.      * 获取分布式锁 
  21.      * 
  22.      * @param lockName 锁名称 
  23.      * @param second   加锁时间(秒) 
  24.      * @return 如果获取到锁,则返回lockId值,否则为null 
  25.      */  
  26.     private String setnxLock(String lockName, int second) {  
  27.         synchronized (this) {  
  28.             //生成随机的Value值  
  29.             String lockId = UUID.randomUUID().toString();  
  30.                 //抢占锁  
  31.                 Long lock = this.jedis.setnx(lockName, lockId);  
  32.                 if (lock == 1) {  
  33.                     //拿到Lock,设置超时时间  
  34.                     this.jedis.expire(lockName, second - 1);  
  35.                     return lockId;  
  36.                 }  
  37.             }  
  38.             return null;  
  39.         }  
  40. }  
3.5、创建自定义的触发器对象,实现Trigger接口 nextExecutionTime 方法
[java]  view plain  copy
  1. public class KyTrigger implements Trigger, Serializable {  
  2.     private String cron;  
  3.     private boolean syncLock;  
  4.     public KyTrigger(KyScheduled kyScheduled){  
  5.         if(kyScheduled.cron() != null && !"".equals(kyScheduled.cron())) {  
  6.             this.cron = kyScheduled.cron();  
  7.         }  
  8.         this.syncLock = kyScheduled.synclock();  
  9.     }  
  10.     public boolean getSyncLock(){  
  11.         return  this.syncLock;  
  12.     }  
  13.     public String getCron() {  
  14.         return cron;  
  15.     }  
  16.     public void setCron(String cron) {  
  17.         if(cron != null && !"".equals(cron)) {  
  18.             this.cron = cron;  
  19.         }  
  20.     }  
  21.     @Override  
  22.     public Date nextExecutionTime(TriggerContext triggerContext) {  
  23.         CronTrigger cronTrigger = new CronTrigger(this.cron);  
  24.         return cronTrigger.nextExecutionTime(triggerContext);  
  25.     }  
  26. }  
3.6、在 KyScheduledExecution 类中创建一个实现Runnable接口的自定义的JOB内部类,需要接收Method和自定义的trigger对象;
[java]  view plain  copy
  1. public class KyScheduledExecution{  
  2.     private Log log = LogFactory.getLog(getClass());  
  3.     /** 
  4.      * 任务对象 
  5.      */  
  6.     public class Job implements Runnable {  
  7.         private Method method;  
  8.         private String lockName;  
  9.         private Object invokeMethod;  
  10.         private Trigger trigger;  
  11.         public String getLockName() {  
  12.             return lockName;  
  13.         }  
  14.         Job(Method m, Trigger t) {  
  15.             this.trigger = t;  
  16.             this.invokeMethod = getBean(m.getDeclaringClass());//获取bean实例  
  17.             this.lockName = m.getDeclaringClass().getName() + "." + m.getName();//构造LockName  
  18.             this.method = m;  
  19.         }  
  20.         @Override  
  21.         public void run() {  
  22.             //获取下次执行时间(秒)  
  23.             long nextTime = (this.trigger.nextExecutionTime(new SimpleTriggerContext()).getTime() - new Date().getTime()) / 1000;  
  24.             //抢占分布式锁  
  25.             String result = setnxLock(this.lockName, (int) nextTime);  
  26.             if (result != null && !"".equals(result)) {  
  27.                 try {  
  28.                     //执行自定义注解的方法  
  29.                     this.method.invoke(this.invokeMethod);  
  30.                 } catch (IllegalAccessException | InvocationTargetException e) {  
  31.                     e.printStackTrace();  
  32.                     log.error(e);  
  33.                 }  
  34.             }  
  35.         }  
  36.     }  
  37. }  
3.7、 KyScheduledExecution 类中 实现 SchedulingConfigurer接口;
[java]  view plain  copy
  1. @Component  
  2. public class KyScheduledExecution implements SchedulingConfigurer{  
  3.     private Log log = LogFactory.getLog(getClass());  
  4.     /** 
  5.      * 配置定时器 
  6.      * 
  7.      * @param taskRegistrar ScheduledTaskRegistrar 
  8.      */  
  9.     @Override  
  10.     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {  
  11.         if (taskRegistrar != null) {  
  12.             for (KyTask kt : kyTaskList) {  
  13.                 Method method = kt.getKyMethod();  
  14.                 //创建触发器  
  15.                 KyTrigger trigger = new KyTrigger(kt.getKyScheduled());  
  16.                 //创建任务  
  17.                 Job job = new Job(method, trigger);  
  18.                 //将任务加入调度器中  
  19.                 taskRegistrar.addTriggerTask(job, trigger);  
  20.             }  
  21.         }  
  22.     }  
  23. }  


代码分解完毕,以上为所有代码!!!


下一篇将引入任务持久化,内部心跳检测定时器任务,以及动态管理定时器的功能;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值