基于Redis实现分布式锁
一. 基本原理
- 基于Redis的setnx命令,如果设置成功,则表示当前进程(线程)获取锁成功,否则说明有其他进程已经获取了锁,需进行等待
- setnx 的key为需要加锁的资源名称(实例中为方法名),value为业务唯一的id
- 加锁时需制定锁的过期时间,避免锁未正常释放而导致的死锁问题
- 加锁时需设置等待超时时间,避免等待时间过长导致系统性能下降
- 释放锁时,与Redis中的value与当前的业务id进行对比,符合才执行释放操作
二. 代码实现
-
加锁的核心操作
/** * @Auther: ZhangShenao * @Date: 2019/3/8 10:29 * @Description:分布式锁信息 */ @Getter @Setter public class LockInfo { //业务唯一id,作为锁的value private String transactionId; //锁的key private String lockKey; //重试次数 private int retryTimes; public static LockInfo valueOf(String transactionId, String lockKey) { LockInfo info = new LockInfo(); info.transactionId = transactionId; info.lockKey = lockKey; info.retryTimes = 0; return info; } public void addRetryTimes(){ ++retryTimes; } }
/** * @Auther: ZhangShenao * @Date: 2019/3/8 10:26 * @Description:基于Redis实现的分布式锁 */ @Component public class RedisLock { @Autowired private StringRedisTemplate redisTemplate; private ValueOperations<String, String> opsForValue; private ThreadLocal<String> localTransactionId = new ThreadLocal<>(); @PostConstruct private void init() { opsForValue = redisTemplate.opsForValue(); } public Optional<LockInfo> tryLock(String lockKey, long timeoutMillis, long expireSeconds) throws InterruptedException { Assert.isTrue(timeoutMillis > 0L, "timeout must be positive!!"); Assert.isTrue(expireSeconds > 0L, "expire must be positive!!"); String transactionId = UUID.randomUUID().toString(); localTransactionId.set(transactionId); LockInfo lockInfo = LockInfo.valueOf(transactionId, lockKey); for (long startTime = System.currentTimeMillis(); System.currentTimeMillis() - startTime < timeoutMillis; lockInfo.addRetryTimes()) { Boolean success = opsForValue.setIfAbsent(lockKey, transactionId); if (Boolean.TRUE.equals(success)) { redisTemplate.expire(lockKey, expireSeconds, TimeUnit.SECONDS); System.err.println(String.format("Thread fetch lock. transactionId: %s, lockKey: %s, retryTimes: %s", lockInfo.getTransactionId(), lockKey, lockInfo.getRetryTimes())); return Optional.of(lockInfo); } Thread.sleep(20L); } //timeout System.err.println(String.format("Thread fetch lock timeout!! transactionId: %s, lockKey: %s", lockInfo.getTransactionId(), lockKey)); return Optional.empty(); } public void release(String lockKey) { String transactionId = Optional.ofNullable(opsForValue.get(lockKey)).orElseThrow(() -> new IllegalStateException("Lock Expired!! key: " + lockKey)); if (!transactionId.equalsIgnoreCase(localTransactionId.get())) { throw new IllegalStateException("Thread try to release lock, but lock is not held by this thread!! threadId: " + Thread.currentThread().getId() + ", lockKey: " + lockKey); } redisTemplate.delete(lockKey); System.err.println(String.format("Thread release lock. transactionId: %s, lockKey: %s", transactionId, lockKey)); } }
-
基于Spring,开发自定义注解和切面,简化对方法加锁的操作
/** * @Auther: ZhangShenao * @Date: 2019/3/8 14:13 * @Description:自定义Lock,标记在方法上,用于指定哪些方法需要自动加Redis锁 */ @Target(value = {ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface Lock { String lockKey() default ""; long expireSeconds(); long timeoutSeconds(); }
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.Optional; /** * @Auther: ZhangShenao * @Date: 2019/3/8 14:05 * @Description:Redis锁切面,拦截标记了@Lock注解的方法,为其执行自动加锁和释放锁的操作 */ @Aspect @Component public class RedisLockAspect { @Autowired private RedisLock redisLock; @Around("@annotation(lock)") public Object addLockForMethods(ProceedingJoinPoint point, Lock lock) throws Throwable { Optional<LockInfo> lockInfo = Optional.empty(); String lockKey = generateLockKey(point, lock); Object result = null; try { lockInfo = redisLock.tryLock(lockKey, lock.expireSeconds(), lock.timeoutSeconds()); result = point.proceed(); return result; } catch (Exception e) { e.printStackTrace(); } finally { lockInfo.ifPresent(l -> redisLock.release(lockKey)); } return result; } private String generateLockKey(ProceedingJoinPoint point, Lock lock) { if (StringUtils.hasText(lock.lockKey())) { return lock.lockKey(); } MethodSignature signature = (MethodSignature) point.getSignature(); String methodName = signature.getMethod().getName(); String className = signature.getMethod().getDeclaringClass().getCanonicalName(); return methodName + "-" + className; } }
-
测试
/**
* @Auther: ZhangShenao
* @Date: 2019/3/8 14:28
* @Description:
*/
@Service
public class DemoService {
@Lock(expireSeconds = 60L, timeoutSeconds = 5L)
public String demoTask() {
return "Do demo task...";
}
}
/**
* @Auther: ZhangShenao
* @Date: 2019/3/8 13:49
* @Description:
*/
@SpringBootApplication
@Import(RedisConfig.class)
@EnableAspectJAutoProxy
public class RedisLockApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(RedisLockApplication.class, args);
DemoService demoService = applicationContext.getBean(DemoService.class);
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
System.err.println(demoService.demoTask());
}
executorService.shutdown();
}
}
结果:
Thread fetch lock. transactionId: 47aa449b-e0b7-407f-b861-52b06668f36e, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 47aa449b-e0b7-407f-b861-52b06668f36e, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: e5ce6b1e-2b02-40a3-aa2b-4ffb00e43f92, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: e5ce6b1e-2b02-40a3-aa2b-4ffb00e43f92, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: 9bde0756-614f-4a97-b57e-87b6dcabf763, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 9bde0756-614f-4a97-b57e-87b6dcabf763, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: 81154275-05de-401d-8f83-1a68ad0f7c3f, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 81154275-05de-401d-8f83-1a68ad0f7c3f, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: 1005e5b7-d1b8-4934-8e31-ceafa2fed891, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 1005e5b7-d1b8-4934-8e31-ceafa2fed891, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: 56eb7b87-dd23-41d3-becc-2058b3b113c1, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 56eb7b87-dd23-41d3-becc-2058b3b113c1, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: b4d46d03-341b-486d-aa1d-878ec56c1272, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: b4d46d03-341b-486d-aa1d-878ec56c1272, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: 8e48df53-a430-422e-90ee-bf90d5f2d455, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 8e48df53-a430-422e-90ee-bf90d5f2d455, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: 1a6963bc-869c-498c-95a1-279eb2b201e3, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: 1a6963bc-869c-498c-95a1-279eb2b201e3, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
Thread fetch lock. transactionId: ff78fe9a-9c49-44e2-b5f7-b7dccd3b792c, lockKey: demoTask-william.redis.lock.DemoService, retryTimes: 0
Thread release lock. transactionId: ff78fe9a-9c49-44e2-b5f7-b7dccd3b792c, lockKey: demoTask-william.redis.lock.DemoService
Do demo task...
可以看到,通过加锁,线程以同步方式顺序执行。
三. 待改进
- 加锁时和setnx操作和expire操作应该保证原子性,可以考虑在程序中执行Lua脚本