Springboot整合Redission及分布式锁


需要安装redis
引入依赖


    org.redisson
    redisson-spring-boot-starter
    3.16.4

配置RedissonClient客户端

@Configuration
public class RedissonConfig {

    @Value("${redisHost}")
    private String redisHost;
    @Value("${redisPassword}")
    private String redisPassword;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        //单机模式  依次设置redis地址和密码
        config.useSingleServer().setAddress(redisHost).setPassword(redisPassword);
        return Redisson.create(config);
    }
}

具有看门狗机制,自动续期,默认续30s 每隔10秒检查异常,最有一次续期检查,自动续到30s

    public String redissonLock(){

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 2; i++) {
            fixedThreadPool.execute(() -> {
                RLock lock = redissonClient.getLock("lockKey");

                lock.lock();
                System.out.println("获取锁");
                try {
                    Thread.sleep(200000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(System.currentTimeMillis() - start);
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }
            });
        }

        return "完成";
    }

尝试拿锁5s后停止重试,返回false 具有看门狗机制,自动延期 默认续30s 100秒后自动释放锁

  public String redissonTryLock() {

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 2; i++) {
            fixedThreadPool.execute(() -> {
                RLock lock = redissonClient.getLock("lockKey");
                try {
                    if (lock.tryLock(5, 10, TimeUnit.SECONDS)) {
                        System.out.println(Thread.currentThread() + "获取锁");
                        Thread.sleep(20000);
                        System.out.println(Thread.currentThread() + "执行完成");
                    } else {
                        System.out.println(Thread.currentThread() + "没有获取锁");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                        System.out.println(Thread.currentThread() + "主动释放锁" + (System.currentTimeMillis() - start));
                    } else {
                        System.out.println(Thread.currentThread() + "已无锁状态" + (System.currentTimeMillis() - start));
                    }
                }
            });
        }

        return "完成";
    }