RedisLock.java 2.7 KB

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