基于redisson分布式锁的spring定时任务

引入依赖

<dependency>
    <groupId>org.redissongroupId>
    <artifactId>redissonartifactId>
    <version>3.8.1version>
dependency>

RedissonClient

@Configuration
public class MyRedissonConfig {

    @Bean
    RedissonClient redisson() throws IOException {
        Config config = new Config();
        //config.useClusterServers().addNodeAddress("127.0.0.1:6379");
        config.useSingleServer().setAddress("redis://192.168.29.128:6379");
        return Redisson.create(config);
    }
    
}

spring的scheduling定时任务类

@Service
public class CronService1 {


    @Autowired
    RedissonClient redisson;

    //@Scheduled(cron = "0 5,6,7,8,9,10,11,12,13,14 * * * ? ")
    @Scheduled(cron = "10 5/1 * * * ? ")// 从5分开始每隔一分钟执行一次
    private void execute() throws Exception {
        //获取Lock锁,设置锁的名称
        RLock lock = redisson.getLock("my-lock");
        if (lock.tryLock(3, TimeUnit.SECONDS)){
            try {
                System.out.println(OffsetDateTime.now() + " &redisson上锁:" + Thread.currentThread().getId());
                //模拟业务处理20秒
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(OffsetDateTime.now() + " &redisson解锁:" + Thread.currentThread().getId());
                //释放
                lock.unlock();
            }
        }
    }
}

你可能感兴趣的:(java基础,javaEE)