Redisson 分布式锁

130 阅读1分钟

Redisson 分布式锁

官方文档:github.com/redisson/re…

配置

  • 单体配置

@Configuration
public class RedissonConfig {

    @Bean
    public RedissonClient redisson() {
        Config config = new Config();

        config.useSingleServer().setAddress("redis://192.168.31.100:6379");

        RedissonClient redissonClient = Redisson.create(config);

        return redissonClient;

    }

}

读写锁的基本使用

  • 注:

    1.读写锁区分了读操作和写操作,读操作使用了一个共享的锁,只要当前没有写锁被占用,读锁是共享的。如果有写锁正在修改数据,那么所有读锁将处于等待状态,直到写锁被释放,读锁就可以读取最新的值。 2.读锁如果没有被释放,写锁尝试获取锁将会被阻塞,直到写锁也释放。 3.读锁之间不会互相阻塞,是共享的。

  • 总结:

  • 读+读 相当于无锁,redis中会增加当前访问线程数个数的读锁

  • 写+读 将等待写锁释放

  • 写+写 阻塞

  • 读+写 有读锁,写锁需要等待

  • 读锁是共享锁,写锁是互斥锁

@GetMapping("/read")
@ResponseBody
public String read() {
    //获取一把读写锁,
    RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
    String s = "";
    //获取读锁
    RLock rLock = readWriteLock.readLock();
    rLock.lock();
    

    try {
        s = redisTemplate.opsForValue().get("key");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        rLock.unlock();
    }

    return s;

}

@GetMapping("/write")
@ResponseBody
public String write() {
    //获取一把读写锁,
    RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");

    String s = "";
    //获取读锁
    RLock wLock = readWriteLock.writeLock();
    wLock.lock();
    String uuid = UUID.randomUUID().toString();

    try {
        redisTemplate.opsForValue().set("key", uuid);
         s = redisTemplate.opsForValue().get("key");
        Thread.sleep(1000 * 10);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        wLock.unlock();
    }

    return s;

}

闭锁(countdownlatch)


@GetMapping("/lockDoor")
@ResponseBody
public String lockDoor() throws InterruptedException {
    RCountDownLatch countDown = redisson.getCountDownLatch("countDown");
    countDown.trySetCount(10);
    System.out.println("设置10个倒数");
    countDown.await();
    return "没人了,关门";
}

@GetMapping("/go/")
@ResponseBody
public String go() {
    RCountDownLatch countDown = redisson.getCountDownLatch("countDown");
    countDown.countDown();
    System.out.println("调用countDown");
    long count = countDown.getCount();


    return "当前count: " + count;
}

信号量(semaphore)

  • 给redis的某一个key的增减。 semaphore.acquire(),会把指定key -1。
  • semaphore.release();+1

@GetMapping("/semaphore")
@ResponseBody
public String semaphore() throws InterruptedException {
    //
    RSemaphore semaphore = redisson.getSemaphore("park");

    semaphore.acquire();[

    return "ok";
}

@GetMapping("/release")
@ResponseBody
public String release() throws InterruptedException {
    //
    RSemaphore semaphore = redisson.getSemaphore("park");

    semaphore.release();

    return "ok";
}