zoukankan      html  css  js  c++  java
  • 集群服务器下使用SpringBoot @Scheduled注解定时任务

    原文:https://blog.csdn.net/huyang1990/article/details/78551578

    SpringBoot提供了 Schedule模块完美支持定时任务的执行

    在实际开发中由于项目部署在分布式或集群服务器上 会导致定时任务多次触发

    因此,使用redis分布锁机制可以有效避免多次执行定时任务

      核心方法是org.springframework.data.redis.core包下的

     setIfAbsent() 方法 返回值为布尔类型

      方法类似redis的SETNX命令 即”SET if Not Exists”

      服务器在执行邮件定时发送任务之前会向redis缓存中写入lock_key即任务锁 表明此服务器正在执行定时任务

      另一台服务器在写入锁时 由于锁已经存在就不做任何操作

      执行定时任务的服务器在执行完成后需释放任务锁

    @Scheduled(cron = "${scheduled.cron}")
        public void scheduler(){
            try {
                if (redisUtil.get("key") == null) {  
                    if(redisUtil.setScheduler("key", "value")){
                        
                        //定时任务执行代码
                        Thread.sleep(3000);
                    }
                }
            } catch (InterruptedException e) {
                logger.error("定时任务异常");
            }finally{
                redisUtil.remove("key");
            }
        }
     

    RedisUtils.java

    public boolean setScheduler(final String key, Object value) {
            boolean result = false;
            try {
                ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
                    return operations.setIfAbsent(key, value);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
  • 相关阅读:
    【转】ORACLE Dataguard安装
    win7 配置微软的深度学习caffe
    深度学习-开源方案
    Python之包管理工具
    C#调用Python脚本的简单示例
    转Python 和C#的交互
    转-使用 CefSharp 在 C# App 中嵌入 Chrome 浏览器
    转-在Mac OS上搭建Python的开发环境
    Weex入门与进阶指南
    A couple of notes about .NET Framework 4.6 setup behaviors
  • 原文地址:https://www.cnblogs.com/shihaiming/p/9714056.html
Copyright © 2011-2022 走看看