@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() {}

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