SpringBoot使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)多機(jī)器部署問題(推薦)
一、使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)
二、定時(shí)任務(wù)多機(jī)器部署解決方案
- 方式一:拆分,單獨(dú)拆分出來,單獨(dú)跑一個(gè)應(yīng)用
- 方式二:基于aop攔截處理(搶占執(zhí)行),只要有一個(gè)執(zhí)行,其它都不執(zhí)行(前提:服務(wù)器時(shí)間一致)
三、基于redis實(shí)現(xiàn)的代碼示例
3.1、基于redis實(shí)現(xiàn)的概述
定時(shí)任務(wù)Aop一樣可以處理的,多臺(tái)同個(gè)任務(wù)類似搶占,先搶到的則打標(biāo)識(shí)記錄在Redis中,根據(jù)有無標(biāo)識(shí)去執(zhí)行任務(wù)
3.2、基于redis實(shí)現(xiàn)的代碼
在使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)的示例基礎(chǔ)上(即此博文鏈接的基礎(chǔ)上)進(jìn)行新增代碼
3.2.1、代碼目錄結(jié)構(gòu)
目錄結(jié)構(gòu)如下圖:

3.2.2、引入依賴包
pom文件引入依賴包
<!-- Redis 配置 排除默認(rèn)啟動(dòng)-->
<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:
#每天幾點(diǎn)幾分執(zhí)行
taskOnecron: 0 25 22 ? * *
#每2分鐘執(zhí)行一次
taskTwocron: 0 0/2 * * * ?
spring:
redis:
#數(shù)據(jù)庫索引
database: 0
host: 127.0.0.1
port: 6379
password:
jedis:
pool:
#最大連接數(shù)
max-active: 8
#最大阻塞等待時(shí)間(負(fù)數(shù)表示沒限制)
max-wait: -1
#最大空閑
max-idle: 8
#最小空閑
min-idle: 0
#連接超時(shí)時(shí)間
timeout: 100003.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 "";
//默認(rèn)超時(shí)時(shí)間(秒)
long TimeOut() default 60;
//默認(rèn)超時(shí)時(shí)間單位 (秒)
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);
//最大重試次數(shù)
private static final Integer MAX_RETRY_COUNT=3;
//鎖前綴
private static final String LOCK_PRE_FIX="lockPreFix";
//鍵
private static final String LOCK_KEY="lockKey";
//超時(shí)時(shí)間
private static final String TIME_OUT="timeOut";
//保護(hù)時(shí)間 2*2^11 =4096
private static final int PROTECT_TIME= 2 << 11;
@Autowired
private CommonRedisHelper commonRedisHelper;
//切點(diǎn)
@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("定時(shí)任務(wù)======>>>redis分布式鎖執(zhí)行發(fā)生異常:"+e.getMessage(),e);
}finally {
//刪除鎖
this.delLock(proceeding);
}
}else{
log.info("定時(shí)任務(wù)======>>>其他服務(wù)器正在執(zhí)行此定時(shí)任務(wù)");
}
}
/**
* 獲取鎖
*/
private boolean getLock(ProceedingJoinPoint proceeding,int count,long currentTime){
//獲取鎖參數(shù)
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("定時(shí)任務(wù)======>>>RedisLock 鎖前綴(LOCK_PRE_FIX)或者鎖名(LOCK_KEY)未設(shè)置");
}
if(commonRedisHelper.setNx(lockPreFix,lockKey,timeOut)){
log.info("定時(shí)任務(wù)======>>>RedisLock:{}線程,已獲取到鎖",Thread.currentThread().getName());
return true;
}else{
//如果當(dāng)前時(shí)間與鎖的時(shí)間差,大于保護(hù)時(shí)間,則強(qiáng)制刪除鎖(防止死鎖)
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("定時(shí)任務(wù)======>>>正在執(zhí)行定時(shí)任務(wù)key:{}",lockKey);
log.info("定時(shí)任務(wù)======>>>RedisLock===={}線程,獲取鎖失敗",Thread.currentThread().getName());
return false;
}
}
/**
* 刪除鎖
*/
private void delLock(ProceedingJoinPoint proceedingJoinPoint){
//獲取鎖參數(shù)
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);
}
/**
* 獲取鎖參數(shù)
* @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 寫鎖時(shí)間
* */
public long getLockValue(String track,String sector){
return (long) redisTemplate.opsForValue().get(track+sector);
}
}
3.2.7、在定時(shí)任務(wù)一中添加自定義注解
定時(shí)任務(wù)一中添加自定義注解,如下圖:

完整代碼如下:
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 定時(shí)任務(wù)一(每天幾點(diǎn)幾分執(zhí)行)
*/
@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("定時(shí)任務(wù)一(每天幾點(diǎn)幾分執(zhí)行一次),執(zhí)行開始時(shí)間:{}",Calendar.getInstance().getTime());
}
@Override
@RedisLock(lockKey = "run",TimeOut = 60)
public void run() {
execute();
}
}
3.2.8、在定時(shí)任務(wù)二中添加自定義注解
定時(shí)任務(wù)二中添加自定義注解,如下圖:

完整代碼如下:
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 定時(shí)任務(wù)一(每幾分鐘執(zhí)行一次,共執(zhí)行幾次)
*/
@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("定時(shí)任務(wù)二:每幾分鐘執(zhí)行一次,執(zhí)行開始時(shí)間:{}", Calendar.getInstance().getTime());
}
@Override
@RedisLock(lockKey = "run",TimeOut = 60)
public void run() {
execute();
}
}3.3、本地嘗試運(yùn)行springboot項(xiàng)目查看輸出結(jié)果
輸出結(jié)果如下所示:

到此這篇關(guān)于SpringBoot使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)多機(jī)器部署問題的文章就介紹到這了,更多相關(guān)SpringBoot多個(gè)定時(shí)任務(wù)多機(jī)器部署內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot定時(shí)任務(wù)SchedulingConfigurer異步多線程實(shí)現(xiàn)方式
- springboot通過SchedulingConfigurer實(shí)現(xiàn)多定時(shí)任務(wù)注冊及動(dòng)態(tài)修改執(zhí)行周期(示例詳解)
- springboot項(xiàng)目使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)的案例代碼
- Spring中利用SchedulingConfigurer實(shí)現(xiàn)動(dòng)態(tài)定時(shí)任務(wù)配置的示例
相關(guān)文章
淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出
這篇文章主要介紹了淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出?具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Spring事件監(jiān)聽器ApplicationListener源碼詳解
這篇文章主要介紹了Spring事件監(jiān)聽器ApplicationListener源碼詳解,ApplicationEvent以及Listener是Spring為我們提供的一個(gè)事件監(jiān)聽、訂閱的實(shí)現(xiàn),內(nèi)部實(shí)現(xiàn)原理是觀察者設(shè)計(jì)模式,需要的朋友可以參考下2023-05-05
Java中的LinkedHashMap及LRU緩存機(jī)制詳解
這篇文章主要介紹了Java中的LinkedHashMap及LRU緩存機(jī)制詳解,LinkedHashMap繼承自HashMap,它的多種操作都是建立在HashMap操作的基礎(chǔ)上的,同HashMap不同的是,LinkedHashMap維護(hù)了一個(gè)Entry的雙向鏈表,保證了插入的Entry中的順序,需要的朋友可以參考下2023-09-09
Springboot獲取前端反饋信息并存入數(shù)據(jù)庫的實(shí)現(xiàn)代碼
這篇文章主要介紹了Springboot獲取前端反饋信息并存入數(shù)據(jù)庫的實(shí)現(xiàn)代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03

