分布式定时任务注解开发

1. 需求

我们在 SpringTask 一文中讲过 @Scheduled 并不支持分布式,这意味着很多定时任务会多次执行,这显然不是我们期望的结果。让我们利用我们讲过的 Spring AOP 来开发一个分布式的 @Scheduled 注解吧!

2. 准备

最好会用 SpringTask、Spring AOP、Redisson (不会也没关系),SpringTask和SpringAOP已经默认继承,只需引入Redisson。

        
            org.redisson
            redisson
            3.16.1
        

3. 思路

  1. 首先需要一个中间件来存储某个定时任务已经有一个服务去执行的相关信息,选择有很多,只要每个微服务都能够访问得到即可,如 zookeeper,Mysql,redis 等等。我们利用 Redis 实现。
  2. 这个信息其实就类似于分布式锁,一个微服务执行定时任务前,先尝试从 Redis 中获取锁,获取到则执行,如果一个服务获取不到锁,就说明已经有一个微服务去执行了这个定时任务,那它就不必执行了。
  3. 那我们如何干预定时任务呢,答案就是 AOP,利用 AOP 的环绕增强,我们可以控制定时任务是否执行。
  4. 接来下就是抢锁和释放锁的逻辑,抢锁成功就允许定时任务执行,失败就不允许定时任务执行。

4. 实现

1. Redisson

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);
    }
}
2. 注解开发

希望在使用上更简单,我用新的注解直接代替原有的 @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 是为了允许服务器之间的时间差。

3. 增强

接下来就是最重要的 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,而不是不断尝试获取,因为我们只需要保证定时任务已经有一个微服务在执行即可。

4.使用

  1. 我们使用简单的方式模拟微服务的情况,指定两个定时任务在同一时间内执行即可。
/**
 * @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 分成 @RequestMappingmethod = RequestMethod.GET 一样,完全没有必要。当我们需要在每个微服务都执行一遍定时任务时,我们可以改造我们的 aop 逻辑:当获取不到 name 时就正常执行。但也没必要,当在每个微服务都执行一遍定时任务时,直接用 @Scheduled 就行啦。

更多原创 shellfish.top

你可能感兴趣的:(java,redis,数据库)