亲宝软件园·资讯

展开

SpringBoot使用SchedulingConfigurer实现多个定时任务多机器部署问题(推荐)

小志的博客 人气:0

一、使用SchedulingConfigurer实现多个定时任务

示例参考lz此博文链接

二、定时任务多机器部署解决方案

三、基于redis实现的代码示例

3.1、基于redis实现的概述

定时任务Aop一样可以处理的,多台同个任务类似抢占,先抢到的则打标识记录在Redis中,根据有无标识去执行任务

3.2、基于redis实现的代码

在使用SchedulingConfigurer实现多个定时任务的示例基础上(即此博文链接的基础上)进行新增代码

3.2.1、代码目录结构

目录结构如下图:

3.2.2、引入依赖包

pom文件引入依赖包

<!-- Redis 配置 排除默认启动-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
     <exclusions>
         <exclusion>
             <groupId>redis.clients</groupId>
             <artifactId>jedis</artifactId>
         </exclusion>
     </exclusions>
 </dependency>
 <!--redis连接池-->
 <dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-pool2</artifactId>
     <version>2.9.0</version>
 </dependency>
 <!--jedis-->
 <dependency>
     <groupId>redis.clients</groupId>
     <artifactId>jedis</artifactId>
     <version>2.9.0</version>
 </dependency>
 <!--aspectj-->
 <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.9.7</version>
 </dependency>

3.2.3、配置文件新增redis连接配置

application.yml配置文件配置

upload:
	#每天几点几分执行
	taskOnecron: 0 25 22 ? * *
	#每2分钟执行一次
	taskTwocron: 0 0/2 * * * ?
spring:
    redis:
        #数据库索引
        database: 0
        host: 127.0.0.1
        port: 6379
        password:
        jedis:
            pool:
                #最大连接数
                max-active: 8
                #最大阻塞等待时间(负数表示没限制)
                max-wait: -1
                #最大空闲
                max-idle: 8
                #最小空闲
                min-idle: 0
                #连接超时时间
        timeout: 10000

3.2.4、自定义redis锁注解类

自定义redis锁注解

package com.xz.jdk11.schedule.aop;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * @author xz
 * @description 自定义redis锁注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface RedisLock {
    //锁前缀
    String lockPrefix() default "SCHEDULE_REDISLOCK:";
    //键
    String lockKey() default "";
    //默认超时时间(秒)
    long TimeOut() default 60;
    //默认超时时间单位 (秒)
    TimeUnit timeUtil() default TimeUnit.SECONDS;
}

3.2.5、自定义redis切面类(即aop类)

redis切面类

package com.xz.jdk11.schedule.aop;

import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xz
 * @description redis锁切面
 */
@Aspect
@Component
public class RedisLockAspect {
    private static final Logger log = LoggerFactory.getLogger(RedisLock.class);

    //最大重试次数
    private static final Integer MAX_RETRY_COUNT=3;
    //锁前缀
    private static final String LOCK_PRE_FIX="lockPreFix";
    //键
    private static final String LOCK_KEY="lockKey";
    //超时时间
    private static final String TIME_OUT="timeOut";
    //保护时间 2*2^11 =4096
    private static final int PROTECT_TIME= 2 << 11;

    @Autowired
    private CommonRedisHelper commonRedisHelper;

    //切点
    @Pointcut("@annotation(com.xz.jdk11.schedule.aop.RedisLock)")
    public void RedisLockAspect(){

    }

    //通知
    @Around(value="RedisLockAspect()")
    public void lockRoundAction(ProceedingJoinPoint proceeding){
        //获取redis锁
        boolean flag = this.getLock(proceeding, 0, System.currentTimeMillis());
        if(flag){
            try {
                proceeding.proceed();
                Thread.sleep(PROTECT_TIME);
            } catch (Throwable e) {
                throw new RuntimeException("定时任务======>>>redis分布式锁执行发生异常:"+e.getMessage(),e);
            }finally {
                //删除锁
                this.delLock(proceeding);
            }
        }else{
            log.info("定时任务======>>>其他服务器正在执行此定时任务");
        }
    }

    /**
     * 获取锁
     */
    private boolean getLock(ProceedingJoinPoint proceeding,int count,long currentTime){
        //获取锁参数
        Map<String, Object> annotationArgs = this.getAnnotationArgs(proceeding);
        String  lockPreFix = (String) annotationArgs.get(LOCK_PRE_FIX);
        String  lockKey = (String) annotationArgs.get(LOCK_KEY);
        long  timeOut = (Long) annotationArgs.get(TIME_OUT);
        if(StrUtil.isEmpty(lockPreFix) || StrUtil.isEmpty(lockKey)){
            throw  new RuntimeException("定时任务======>>>RedisLock 锁前缀(LOCK_PRE_FIX)或者锁名(LOCK_KEY)未设置");
        }
        if(commonRedisHelper.setNx(lockPreFix,lockKey,timeOut)){
            log.info("定时任务======>>>RedisLock:{}线程,已获取到锁",Thread.currentThread().getName());
            return true;
        }else{
            //如果当前时间与锁的时间差,大于保护时间,则强制删除锁(防止死锁)
            long creatTime = commonRedisHelper.getLockValue(lockPreFix, lockKey);
            if((currentTime - creatTime) >timeOut * 1000 + PROTECT_TIME){
                count ++;
                if(count > MAX_RETRY_COUNT){
                    return  false;
                }
                commonRedisHelper.delete(lockPreFix,lockKey);
                getLock(proceeding,count,currentTime);
            }
            log.info("定时任务======>>>正在执行定时任务key:{}",lockKey);
            log.info("定时任务======>>>RedisLock===={}线程,获取锁失败",Thread.currentThread().getName());
            return false;
        }
    }

    /**
     * 删除锁
     */
    private void delLock(ProceedingJoinPoint proceedingJoinPoint){
        //获取锁参数
        Map<String, Object> annotationArgs = this.getAnnotationArgs(proceedingJoinPoint);
        String  lockPreFix = (String) annotationArgs.get(LOCK_PRE_FIX);
        String  lockKey = (String) annotationArgs.get(LOCK_KEY);
        //删除锁
        commonRedisHelper.delete(lockPreFix,lockKey);
    }

    /**
     * 获取锁参数
     * @param proceeding
     * */
    public Map<String,Object> getAnnotationArgs(ProceedingJoinPoint proceeding){
        Class<?> target = proceeding.getTarget().getClass();
        //获取所有方法
        Method[] methods = target.getMethods();
        //获取方法名称
        String methodName = proceeding.getSignature().getName();
        for(Method method:methods){
            if(method.getName().equals(methodName)){
                HashMap<String, Object> hashMap = new HashMap<>();
                RedisLock redisLock = method.getAnnotation(RedisLock.class);
                hashMap.put(LOCK_PRE_FIX,redisLock.lockPrefix());
                hashMap.put(LOCK_KEY,redisLock.lockKey());
                hashMap.put(TIME_OUT,redisLock.timeUtil().toSeconds(redisLock.TimeOut()));
                return hashMap;
            }
        }
        return new HashMap<>();
    }
}

3.2.6、自定义redis命令操作类

redis命令操作类

package com.xz.jdk11.schedule.aop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author xz
 * @description redis命令操作类
 */
@Component
public class CommonRedisHelper {
    @Autowired
    RedisTemplate<Object,Object> redisTemplate;
    /**
     * 添加分布式锁
     * */
    public boolean setNx(String track,String sector,long timeout){
        boolean flag =false;
        ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
        flag=valueOperations.setIfAbsent(track+sector,System.currentTimeMillis());
        if(flag){
            valueOperations.set(track+sector,getLockValue(track,sector),timeout, TimeUnit.SECONDS);
        }
        return flag;
    }

    /**
     * 删除锁
     * @param lockPreFix 前缀
     * @param key 键
     * */
    public void delete(String lockPreFix,String key){
        redisTemplate.delete(lockPreFix+key);
    }

    /**
     * 查询锁
     * @return 写锁时间
     * */
    public long getLockValue(String track,String sector){
        return (long) redisTemplate.opsForValue().get(track+sector);
    }
}

3.2.7、在定时任务一中添加自定义注解

定时任务一中添加自定义注解,如下图:

完整代码如下:

package com.xz.jdk11.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Calendar;

/**
 * @author xz
 * @description 定时任务一(每天几点几分执行)
 */
@Slf4j
@Component
public class TaskOne implements BaskTask{
    @Value("${upload.taskOnecron}")
    private String taskOnecron;

    @Override
    public String getCron() {
        return taskOnecron;
    }

    @Override
    public void execute() {
        log.info("定时任务一(每天几点几分执行一次),执行开始时间:{}",Calendar.getInstance().getTime());
    }
    @Override
    @RedisLock(lockKey = "run",TimeOut = 60)
    public void run() {
        execute();
    }
}

3.2.8、在定时任务二中添加自定义注解

定时任务二中添加自定义注解,如下图:

完整代码如下:

package com.xz.jdk11.schedule;
import com.xz.jdk11.schedule.aop.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;

/**
 * @author xz
 * @description 定时任务一(每几分钟执行一次,共执行几次)
 */
@Slf4j
@Component
public class TaskTwo implements BaskTask{
    @Value("${upload.taskTwocron}")
    private String taskTwocron;

    @Override
    public String getCron() {
        return taskTwocron;
    }

    @Override
    public void execute() {
        log.info("定时任务二:每几分钟执行一次,执行开始时间:{}", Calendar.getInstance().getTime());
    }

    @Override
    @RedisLock(lockKey = "run",TimeOut = 60)
    public void run() {
        execute();
    }
}

3.3、本地尝试运行springboot项目查看输出结果

输出结果如下所示:

加载全部内容

相关教程
猜你喜欢
用户评论