当前位置:网站首页>Redis distributed lock, lock code logic

Redis distributed lock, lock code logic

2022-07-05 02:11:00 I use mosquito repellent incense






       
public boolean lock(String key, String value) {
if(redisTemplate.opsForValue().setIfAbsent(key, value)) {
return true;
}
String currentValue = redisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(currentValue)
&& Long.parseLong(currentValue) < System.currentTimeMillis()) {

String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
return true;
}
}
return false;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.


Suppose there are two threads now A and B At the same time lock() Method , That is, the of these two threads value It's exactly the same , All for value=2020-12-19, And they all carry out ​​String oldValue = redisTemplate.opsForValue().getAndSet(key, value);​​, There will be one to execute first and then :

If a thread A Execute first , Back to ​​oldValue=2020-12-18​​​, Simultaneous setting ​​value = 2020-12-19​​​, because ​​oldvalue=currentValue​​ return true, namely A The thread is locked ;

here B The thread continues to execute , Back to ​​oldValue=2020-12-19,oldvalue!=currentValue​​, return false, Locking failed

So the logic of this code is to lock only one thread



原网站

版权声明
本文为[I use mosquito repellent incense]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140942238285.html