• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Redis implements distributed lock

King Wang

1 月 3, 2022
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class RedisLock {
@Autowired
private StringRedisTemplate redisTemplate;
/* Lock */
public boolean lock(String key,String value){
if (redisTemplate.opsForValue().setIfAbsent(key,value)){
return true;
}
String currentValue = redisTemplate.opsForValue().get(key);
// If Redis Lock time expired
if (!StringUtils.isEmpty(currentValue)
&& Long.parseLong(currentValue) < System.currentTimeMillis()){
// The time at which the last lock was acquired
String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)){
return true;
}
}
return false;
}
/* Unlock */
public void unlock(String key,String value){
try {
String currentValue = redisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)){
redisTemplate.opsForValue().getOperations().delete(key);
}
}catch (Exception e){
throw new RuntimeException("【Redis Distributed lock 】 Unlock failure ");
}
}
}

The above is the use of Redis To lock and unlock concurrent case code , It can be used to solve the problem of high concurrency seconds killing exceeding the inventory number .

发表回复