ReadWriteLock读写锁
并发写需要等待,并发读等于无锁
- 读和写是同一把锁控制
- 只要写锁没释放,读锁就必须等待,反之一样
- 允许多个读锁 和 仅允许一个 写锁
- 读锁是共享锁,写锁是排他锁(互斥锁)
- 读写锁是同一把锁 RReadWriteLock lock = redissonClient.getReadWriteLock(“rw-lock”); get set取值也是同一个对象
需求:保证获取的是最新的数据? 怎么操作?
更新完数据就释放写锁,定时任务 判断锁是否存在,如果锁存在,等锁释放后取值
这里是先执行写锁再执行读锁,当写锁释放时,写锁读锁同时渲染数据
//写锁
@GetMapping("/write")
@ResponseBody
public String writeValue(){
//读写锁是同一把锁
RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
RLock writeLock = lock.writeLock();
String uuid = "";
try {
uuid = UUID.randomUUID().toString();
writeLock.lock();
System.out.println("写锁占用成功");
Thread.sleep(30000);
redisTemplate.opsForValue().set("writeValue", uuid);
} catch (Exception e) {
e.printStackTrace();
} finally {
//写锁释放,读锁才能使用
writeLock.unlock();
System.out.println("写锁释放完成");
}
return uuid;
}
//读锁
@GetMapping("/read")
@ResponseBody
public String readValue(){
RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
RLock readLock = lock.readLock();
String uuid = "";
try {
readLock.lock();
uuid = redisTemplate.opsForValue().get("writeValue");
System.out.println("读锁占用成功");
Thread.sleep(30000);
} catch (Exception e) {
e.printStackTrace();
} finally {
readLock.unlock();
System.out.println("读锁释放完成");
}
return uuid;
}
先读后写,读锁释放,写锁才能占用,这里就可以看出来读和写是同一把锁