RedisLock.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.example.demo.util;
  2. import cn.hutool.core.util.StrUtil;
  3. import org.springframework.data.redis.core.StringRedisTemplate;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class RedisLock {
  7. private final StringRedisTemplate stringRedisTemplate;
  8. public RedisLock(StringRedisTemplate stringRedisTemplate) {
  9. this.stringRedisTemplate = stringRedisTemplate;
  10. }
  11. /**
  12. * 加锁
  13. * @param lockKey 加锁的Key
  14. * @param timeStamp 时间戳:当前时间+超时时间
  15. * @return
  16. */
  17. public boolean lock(String lockKey,String timeStamp){
  18. if(stringRedisTemplate.opsForValue().setIfAbsent(lockKey, timeStamp)){
  19. // 对应setnx命令,可以成功设置,也就是key不存在,获得锁成功
  20. return true;
  21. }
  22. //设置失败,获得锁失败
  23. // 判断锁超时 - 防止原来的操作异常,没有运行解锁操作 ,防止死锁
  24. String currentLock = stringRedisTemplate.opsForValue().get(lockKey);
  25. // 如果锁过期 currentLock不为空且小于当前时间
  26. if(StrUtil.isNotEmpty(currentLock) && Long.parseLong(currentLock) < System.currentTimeMillis()){
  27. //如果lockKey对应的锁已经存在,获取上一次设置的时间戳之后并重置lockKey对应的锁的时间戳
  28. String preLock = stringRedisTemplate.opsForValue().getAndSet(lockKey, timeStamp);
  29. //假设两个线程同时进来这里,因为key被占用了,而且锁过期了。
  30. //获取的值currentLock=A(get取的旧的值肯定是一样的),两个线程的timeStamp都是B,key都是K.锁时间已经过期了。
  31. //而这里面的getAndSet一次只会一个执行,也就是一个执行之后,上一个的timeStamp已经变成了B。
  32. //只有一个线程获取的上一个值会是A,另一个线程拿到的值是B。
  33. if(StrUtil.isNotEmpty(preLock) && preLock.equals(currentLock)){
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. /**
  40. * 释放锁
  41. * @param lockKey
  42. * @param timeStamp
  43. */
  44. public void release(String lockKey,String timeStamp){
  45. try {
  46. String currentValue = stringRedisTemplate.opsForValue().get(lockKey);
  47. if(!StrUtil.isEmpty(currentValue) && currentValue.equals(timeStamp) ){
  48. // 删除锁状态
  49. stringRedisTemplate.opsForValue().getOperations().delete(lockKey);
  50. }
  51. } catch (Exception e) {
  52. System.out.println("警报!警报!警报!解锁异常");
  53. }
  54. }
  55. }