我们在 SpringTask 一文中讲过 @Scheduled
并不支持分布式,这意味着很多定时任务会多次执行,这显然不是我们期望的结果。让我们利用我们讲过的 Spring AOP 来开发一个分布式的 @Scheduled
注解吧!
最好会用 SpringTask、Spring AOP、Redisson (不会也没关系),SpringTask和SpringAOP已经默认继承,只需引入Redisson。
org.redisson
redisson
3.16.1
Redisson为我们实现好了分布式锁,我们只需要配置客户端
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* redis为单例情况下的配置
* @Description: Redisson客户端
* @Author: Shell Fish
* @Date: 2021/8/4
* @Version: V1.0
*/
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
String redisHost;
@Value("${spring.redis.port}")
Integer redisPort;
@Value("${spring.redis.password}")
String redisPassword;
@Bean
public RedissonClient redissonClient(){
Config config = new Config();
config.useSingleServer().setConnectionMinimumIdleSize(10);
config.useSingleServer().setAddress("redis://"+redisHost+":"+redisPort).setPassword(redisPassword).setDatabase(0);
return Redisson.create(config);
}
}
希望在使用上更简单,我用新的注解直接代替原有的 @Scheduled
注解,这里我用 SpringMvc 的 @GetMapping
强化 @RequestMapping
的方式强化 @Scheduled
,就像这样
import org.springframework.core.annotation.AliasFor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.annotation.*;
/**
* name:你需要保证name所有的在定时任务是唯一的(每个name会对应一个锁)
*
* maxLockTime:最大锁时间(防止死锁)
*
* minLockTime:最小锁时间(服务器之间时间差最大限制值),一个定时任务需要在 12:00:00 的时候执行,允许这个定时任务延时 minLockTime 毫秒执行,
* @FishScheduled 仍可以保证分布式定时任务的控制。定时任务有时会延时几秒执行,可以通过增大 minLockTime 来控制
*
* @author: Shell Fish
* @since: 1.0
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Scheduled
public @interface FishScheduled{
/**
* redis key.你需要保证每个定时任务都有一个唯一的name
*/
String name();
/**
* 最大锁时间,默认16秒
*/
long maxLockTime() default 16000L;
/**
* 最小锁时间,默认800毫秒
*/
long minLockTime() default 800L;
String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;
@AliasFor(annotation = Scheduled.class)
String cron() default "";
@AliasFor(annotation = Scheduled.class)
String zone() default "";
@AliasFor(annotation = Scheduled.class)
long fixedDelay() default -1;
@AliasFor(annotation = Scheduled.class)
String fixedDelayString() default "";
@AliasFor(annotation = Scheduled.class)
long fixedRate() default -1;
@AliasFor(annotation = Scheduled.class)
String fixedRateString() default "";
@AliasFor(annotation = Scheduled.class)
long initialDelay() default -1;
@AliasFor(annotation = Scheduled.class)
String initialDelayString() default "";
}
name将用于指定分布式锁的 key 的一部分,比较重要的是需要指定 maxLockTime
最大锁时间,为了防止极个别情况加锁无法释放导致死锁,我们指定分布式锁的过期时间。minLockTime
是为了允许服务器之间的时间差。
接下来就是最重要的 aop 部分,因为需要控制定时任务是否执行,所以我们用到环绕增强。就像这样。
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.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @Description: 分布式定时任务注解
* @Author: Shell Fish
* @Date: 2021/8/4
* @Version: V1.0
*/
@Aspect
@Component
public class ShellLockAop {
@Autowired
private RedissonClient redissonClient;
@Value("${spring.application.name}")
private String moduleName;
private static final String REDIS_PREFIX = "fishLock:";
@Pointcut(value = "@annotation(fishScheduled)" ,argNames = "fishScheduled")
public void pointcut(FishScheduled fishScheduled) {
}
@Around(value = "pointcut(fishScheduled)",argNames = "joinPoint,fishScheduled" )
public void before(ProceedingJoinPoint joinPoint, FishScheduled fishScheduled) throws Throwable {
String lockName = fishScheduled.name();
long max = fishScheduled.maxLockTime();
long min = fishScheduled.minLockTime();
String module = Objects.isNull(moduleName)?"public":moduleName;
String key = REDIS_PREFIX + module +":"+ lockName;
RLock lock = redissonClient.getLock(key);
boolean tryLock = false;
TimeInterval timer = null;
try {
System.out.println(Thread.currentThread().getName() + ":尝试上锁: time=" + DateUtil.now());
tryLock = lock.tryLock(0, max, TimeUnit.MILLISECONDS);
if(tryLock){
System.out.println(Thread.currentThread().getName() + ":上锁成功: time=" + DateUtil.now());
timer = DateUtil.timer();
joinPoint.proceed();
}else {
System.out.println(Thread.currentThread().getName() + ":上锁失败: time=" + DateUtil.now());
}
}catch (Throwable e) {
e.printStackTrace();
throw e;
} finally {
if(tryLock){
long interval = timer.interval();
TimeUnit.MILLISECONDS.sleep(min-interval);
lock.unlock();
System.out.println(Thread.currentThread().getName() + ":解锁成功: time=" + DateUtil.now());
}
}
}
}
我们的分布式锁的 key 由 REDIS_PREFIX + ModuleName + name
三部分组成,利用 @Pointcut
指定切入点,在环绕增强使用该切入点。有一点注意,lock.tryLock
的第一个参数是尝试加锁的时间,我们需要将其指定为 0,如果已经有微服务加过锁了,就会返回 false
,而不是不断尝试获取,因为我们只需要保证定时任务已经有一个微服务在执行即可。
/**
* @Description: 模拟推送 订单状态
* @Author: Shell Fish
* @Date: 2021/7/30
* @Version: V1.0
*/
@Component
@Slf4j
@EnableScheduling
@EnableAsync
public class Producer {
@Async
@FishScheduled(name = "producer", maxLockTime = 1000 * 60 * 60, cron = "0 */1 * * * ?")
public void produce() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
DefaultMQProducer producer = new DefaultMQProducer("order_producer");
producer.setNamesrvAddr(MyConfiguration.nameServer);
producer.start();
String[] tags = new String[]{"TagA", "TagC", "TagD"};
for (int i = 0; i < 5; i++) {
OrderLifeCyclePush pusher = OrderLifeCyclePush.builder().parkOrderId("1").berthName("aaa").berthId("1414527851947855874").parkOrderId("1").voice("倒车请注意").build();
Message msg = new Message(Topic.ORDER_LIFE_CYCLE_PUSH_TOPIC.getName(), tags[i % tags.length], JSONUtil.toJsonStr(pusher).getBytes());
SendResult sendResult = producer.send(msg);
log.info("生产者:" + sendResult.toString());
}
producer.shutdown();
}
@Async
@FishScheduled(name = "producer", maxLockTime = 1000 * 60*60, cron = "0 */1 * * * ?")
public void produce1() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
DefaultMQProducer producer = new DefaultMQProducer("order_producer");
producer.setNamesrvAddr(MyConfiguration.nameServer);
producer.start();
String[] tags = new String[]{"TagA", "TagC", "TagD"};
for (int i = 0; i < 5; i++) {
OrderLifeCyclePush pusher = OrderLifeCyclePush.builder().parkOrderId("1").berthName("aaa").berthId("1414527851947855874").parkOrderId("1").voice("倒车请注意").build();
Message msg = new Message(Topic.ORDER_LIFE_CYCLE_PUSH_TOPIC.getName(), tags[i % tags.length], JSONUtil.toJsonStr(pusher).getBytes());
SendResult sendResult = producer.send(msg);
log.info("生产者:" + sendResult.toString());
}
producer.shutdown();
}
}
直接复制一个已有的定时任务,模拟两个微服务(定时任务中是RocketMQ的生产者的订单推送实例),使用我们开发好的 @FishScheduled
注解,指定定时任务的 name 和 maxLockTime,其他和使用 @Scheduled
注解一致,我们使用到了 cron表达式 ,每分钟执行一次定时任务。
2. 结果
// Result
task-3:上锁成功:producer
task-4:上锁失败:producer
task-3:解锁成功
// A minute later
task-6:上锁失败:producer
task-5:上锁成功:producer
task-5:解锁成功
// ...
task-3 抢到了锁并上锁成功后 task-4 抢锁失败后没有再尝试抢锁,不会再执行定时任务,task-3 定时任务执行完毕后释放锁。一分钟后情况类似。
4. 总结
我们也可以将 @FishScheduled
分为 @Fish
和 @Scheduled
,但这样就像 @GettingMapping
分成 @RequestMapping
和 method = RequestMethod.GET
一样,完全没有必要。当我们需要在每个微服务都执行一遍定时任务时,我们可以改造我们的 aop 逻辑:当获取不到 name 时就正常执行。但也没必要,当在每个微服务都执行一遍定时任务时,直接用 @Scheduled
就行啦。
更多原创 shellfish.top