保证一定读到最新数据,修改期间,写锁是一个排他锁/互斥锁。读锁是一个共享锁。(相当于操作系统中的读写者问题)
写锁没释放读必须等待
测试如下:
@Autowired
RedissonClient redissonClient;
@Autowired
StringRedisTemplate redisTemplate;
@GetMapping("/write")
@ResponseBody
public String writeValue(){
RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
RLock rLock = readWriteLock.writeLock();//获取写锁
String s = null;
try {
//1、该数据加写锁,读数据加读锁
rLock.lock();
s = UUID.randomUUID().toString();
Thread.sleep(30000);
redisTemplate.opsForValue().set("writeValue", s);
}catch (Exception e){
e.printStackTrace();
}finally {
rLock.unlock();//解锁
}
return s;
}
@GetMapping("/read")
@ResponseBody
public String readValue(){
RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
RLock rLock = readWriteLock.readLock();//获取读锁
String s = null;
try {
rLock.lock();
s = redisTemplate.opsForValue().get("writeValue");
}catch (Exception e){
e.printStackTrace();
}finally {
rLock.unlock();
}
return s;
}
标签:Redisson,String,写锁,lock,rLock,---,73,readWriteLock
From: https://www.cnblogs.com/morehair/p/17083956.html