@SchedulerLock基于 redis 配置

SchedulerLock的作用,确保任务在同一时刻最多执行一次。如果一个任务正在一个节点上执行,则它将获得一个锁,该锁将阻止从另一个节点(或线程)执行同一任务。如果一个任务已经在一个节点上执行,则在其他节点上的执行不会等待,只需跳过它即可 。
ShedLock使用Mongo,JDBC数据库,Redis,Hazelcast,ZooKeeper或其他外部存储进行协调,即通过外部存储来实现锁机制;

  1. maven 引入依赖
 <dependency>
            <groupId>net.javacrumbs.shedlock</groupId>
            <artifactId>shedlock-spring</artifactId>
            <version>2.2.0</version>
        </dependency>
                <dependency>
            <groupId>net.javacrumbs.shedlock</groupId>
            <artifactId>shedlock-provider-redis-spring</artifactId>
            <version>2.3.0</version>
        </dependency>     
  1. 配置 redis信息 格式不要错 若用keewidb 关键字也需要用redis .
spring:
  profiles: prod
  redis:
    host:  
    port: 
    password: 
    connectTimeout: 2000
    soTimeout: 2000
    jedis:
      pool:
        max-idle: 30
        min-idle: 20
        max-wait: -1
        max-active: 30
        minEvictableIdleTimeMillis: 600000
        time-between-eviction-runs: 300000
  1. redisson 单例配置

  2. `@Configuration
    public class RedissonConfig {

    @Value(“ s p r i n g . k e e w i d b . h o s t " ) p r i v a t e S t r i n g h o s t ; @ V a l u e ( " {spring.keewidb.host}") private String host; @Value(" spring.keewidb.host")privateStringhost;@Value("{spring.keewidb.port}”)
    private String port;
    @Value(“${spring.keewidb.password}”)
    private String password;

    @Bean(destroyMethod=“shutdown”)
    public RedissonClient redissonClient() throws IOException {
    Config config = new Config();
    SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(“redis://”+host+“:”+port);

    if (StringUtils.isNotEmpty(password)) {
        singleServerConfig.setPassword(password);
    }
    System.out.println("redisson: "+config.getTransportMode());
    return Redisson.create(config);
    

    }
    }`

  3. ScheduledLockConfig 配置

  4. `@Configuration
    @EnableScheduling
    @EnableSchedulerLock(defaultLockAtMostFor = “PT10M”)
    public class ScheduledLockConfig {
    @Value(“${spring.profiles}”)
    private String env;

    @Bean
    public LockProvider lockProvider(RedisConnectionFactory connectionFactory) {
    return new RedisLockProvider(connectionFactory,env);
    }

    @Bean
    public ScheduledLockConfiguration scheduledLockConfiguration(LockProvider lockProvider) {
    return ScheduledLockConfigurationBuilder.withLockProvider(lockProvider)
    .withPoolSize(10)
    .withDefaultLockAtMostFor(Duration.ofMinutes(10)).build();
    }
    }
    `

  5. 设置定时任务(注解)

  6. @Scheduled(cron = "10 1 10 * * ?") @SchedulerLock(name = "lock", lockAtLeastForString = "PT1M", lockAtMostForString = "PT5M") public void checkEquipmentNumTasks() {}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值