DistributedLock.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package com.java110.utils.lock;
  2. import com.java110.utils.cache.BaseCache;
  3. import redis.clients.jedis.Jedis;
  4. import java.util.Collections;
  5. import java.util.UUID;
  6. /**
  7. * 分布式事务锁
  8. * add by wuxw 2020-01-11
  9. */
  10. public class DistributedLock extends BaseCache {
  11. private static final String LOCK_SUCCESS = "OK";
  12. private static final String SET_IF_NOT_EXIST = "NX";
  13. private static final String SET_WITH_EXPIRE_TIME = "PX";
  14. private static final int DEFAULT_EXPIRE_TIME = 1000;
  15. private static final Long RELEASE_SUCCESS = 1L;
  16. /**
  17. * 获取UUID
  18. * @return
  19. */
  20. public static String getLockUUID(){
  21. return UUID.randomUUID().toString();
  22. }
  23. /**
  24. * 等待获取锁
  25. *
  26. * @param lockKey 锁
  27. * @param requestId 请求标识
  28. * @return
  29. */
  30. public static boolean waitGetDistributedLock(String lockKey, String requestId) {
  31. return waitGetDistributedLock(lockKey, requestId, DEFAULT_EXPIRE_TIME);
  32. }
  33. public static boolean waitGetDistributedLock(String lockKey, String requestId, int expireTime) {
  34. Jedis redis = null;
  35. try {
  36. redis = getJedis();
  37. while (true) {
  38. if (tryGetDistributedLock(redis, lockKey, requestId, expireTime)) {
  39. return true;
  40. }
  41. }
  42. } finally {
  43. if (redis != null) {
  44. redis.close();
  45. }
  46. }
  47. }
  48. /**
  49. * 尝试获取分布式锁
  50. *
  51. * @param lockKey 锁
  52. * @param requestId 请求标识
  53. * @param expireTime 超期时间
  54. * @return 是否获取成功
  55. */
  56. public static boolean tryGetDistributedLock(Jedis redis, String lockKey, String requestId, int expireTime) {
  57. String result = redis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
  58. if (LOCK_SUCCESS.equals(result)) {
  59. return true;
  60. }
  61. return false;
  62. }
  63. /**
  64. * 释放分布式锁
  65. *
  66. * @param lockKey 锁
  67. * @param requestId 请求标识
  68. * @return 是否释放成功
  69. */
  70. public static boolean releaseDistributedLock(String lockKey, String requestId) {
  71. Jedis redis = null;
  72. try {
  73. redis = getJedis();
  74. String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  75. Object result = redis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
  76. if (RELEASE_SUCCESS.equals(result)) {
  77. return true;
  78. }
  79. return false;
  80. } finally {
  81. if (redis != null) {
  82. redis.close();
  83. }
  84. }
  85. }
  86. }