CommonRedisHelper.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package cn.efunbox.base.util;
  2. import org.apache.commons.lang3.StringUtils;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * CommonRedisHelper
  8. * Created by wangys on 2019/04/09
  9. */
  10. /**
  11. * Description: 通用Redis帮助类
  12. * User: zhouzhou
  13. * Date: 2018-09-05
  14. * Time: 15:39
  15. */
  16. @Component
  17. public class CommonRedisHelper {
  18. @Autowired
  19. private RedisTemplate<String, String> redisTemplate;
  20. /**
  21. * 加锁
  22. *
  23. * @param key 键
  24. * @param value 当前时间 + 超时时间
  25. * @return 是否拿到锁
  26. */
  27. public boolean lock(String key, String value) {
  28. if (redisTemplate.opsForValue().setIfAbsent(key, value)) {
  29. return true;
  30. }
  31. String currentValue = redisTemplate.opsForValue().get(key);
  32. //如果锁过期
  33. if (!StringUtils.isEmpty(currentValue)
  34. && Long.parseLong(currentValue) < System.currentTimeMillis()) {
  35. String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
  36. //是否已被别人抢占
  37. return StringUtils.isNotEmpty(oldValue) && oldValue.equals(currentValue);
  38. }
  39. return false;
  40. }
  41. /**
  42. * 解锁
  43. *
  44. * @param key 键
  45. * @param value 当前时间 + 超时时间
  46. */
  47. public void unlock(String key, String value) {
  48. try {
  49. String currentValue = redisTemplate.opsForValue().get(key);
  50. if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
  51. redisTemplate.opsForValue().getOperations().delete(key);
  52. }
  53. } catch (Exception e) {
  54. // log.error("redis解锁异常");
  55. }
  56. }
  57. }