package com.ccf.service.lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLock {
Logger logger = LoggerFactory.getLogger(RedisLock.class);
@Resource
private RedisTemplate<String,String> redisTemplate;
//处理可重入的问题
ThreadLocal<Map<String, Integer>> threadLocal = ThreadLocal.withInitial(HashMap::new);
/**
*
* @param lockKey 分布式锁key
* @param requestId 锁的值
* @param acquireTimeout 尝试获取锁的超时时间,单位毫秒
* @param expireTime 锁的过期时间,单位毫秒
* @return
*/
public boolean tryLock(String lockKey,String requestId,long acquireTimeout,long expireTime){
Map<String,Integer> value = threadLocal.get();
if(value.containsKey(lockKey)){
value.put(lockKey,value.get(lockKey) + 1);
return true;
}
long end = System.currentTimeMillis() + acquireTimeout;
while(System.currentTimeMillis() < end){
Boolean result = redisTemplate.boundValueOps(lockKey).setIfAbsent(requestId,expireTime, TimeUnit.MILLISECONDS);
if (result) {
value.put(lockKey,1);
return true;
}
try {
//尝试获取锁失败,休眠10ms再试
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("RedisLock中断异常",e);
return false;
}
}
return false;
}
/**
* 尝试释放分布式锁
* @param lockKey
* @param requestId
*/
public void tryRelease(String lockKey,String requestId){
//处理可重入的问题
Map<String,Integer> value = threadLocal.get();
//说明获取到锁的
if(value.containsKey(lockKey)){
Integer num = value.get(lockKey) - 1;
if(num <= 0){
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setResultType(Long.class);
redisScript.setScriptText(script);
Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),requestId);
if (result.equals(1L)) {
value.remove(lockKey);
}
}else{
value.put(lockKey,num);
}
}else{
logger.warn("未获取到分布式,不能释放锁");
}
}
}
Redis实现可重入分布式锁
于 2022-04-26 11:00:46 首次发布
该博客介绍了一个基于Spring Data Redis实现的可重入分布式锁`RedisLock`。这个锁利用了Redis的`setIfAbsent`方法尝试获取锁,并通过ThreadLocal处理可重入问题。在释放锁时,通过lua脚本确保只有持有锁的请求才能释放,并且处理了可重入计数的减少。
摘要由CSDN通过智能技术生成