1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
| @Service public class RedisDistributedLock { private static final Logger logger = LoggerFactory.getLogger(RedisDistributedLock.class); @Autowired private RedisTemplate<String, String> redisTemplate; private static final String LOCK_PREFIX = "distributed:lock:"; private static final int DEFAULT_EXPIRE_TIME = 30; private static final int DEFAULT_WAIT_TIME = 10;
public boolean acquireLock(String lockKey, String lockValue, int expireTime) { String key = LOCK_PREFIX + lockKey; try { Boolean result = redisTemplate.opsForValue().setIfAbsent(key, lockValue, Duration.ofSeconds(expireTime)); if (Boolean.TRUE.equals(result)) { logger.info("成功获取分布式锁: {}", lockKey); return true; } else { logger.warn("获取分布式锁失败: {}", lockKey); return false; } } catch (Exception e) { logger.error("获取分布式锁异常: {}", e.getMessage(), e); return false; } }
public boolean releaseLock(String lockKey, String lockValue) { String key = LOCK_PREFIX + lockKey; try { String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then " + " return redis.call('del', KEYS[1]) " + "else " + " return 0 " + "end"; Long result = redisTemplate.execute( (RedisCallback<Long>) connection -> connection.eval(luaScript.getBytes(), ReturnType.INTEGER, 1, key.getBytes(), lockValue.getBytes()) ); if (result != null && result == 1) { logger.info("成功释放分布式锁: {}", lockKey); return true; } else { logger.warn("释放分布式锁失败: {}", lockKey); return false; } } catch (Exception e) { logger.error("释放分布式锁异常: {}", e.getMessage(), e); return false; } }
public boolean tryLock(String lockKey, String lockValue, int expireTime, int waitTime) { long startTime = System.currentTimeMillis(); long endTime = startTime + waitTime * 1000; while (System.currentTimeMillis() < endTime) { if (acquireLock(lockKey, lockValue, expireTime)) { return true; } try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } return false; }
public boolean renewLock(String lockKey, String lockValue, int expireTime) { String key = LOCK_PREFIX + lockKey; try { String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then " + " return redis.call('expire', KEYS[1], ARGV[2]) " + "else " + " return 0 " + "end"; Long result = redisTemplate.execute( (RedisCallback<Long>) connection -> connection.eval(luaScript.getBytes(), ReturnType.INTEGER, 1, key.getBytes(), lockValue.getBytes(), String.valueOf(expireTime).getBytes()) ); return result != null && result == 1; } catch (Exception e) { logger.error("锁续期异常: {}", e.getMessage(), e); return false; } }
public static class DistributedLockUtil {
public static <T> T executeWithLock(RedisDistributedLock lockService, String lockKey, String lockValue, int expireTime, Supplier<T> operation) { boolean acquired = false; try { acquired = lockService.acquireLock(lockKey, lockValue, expireTime); if (acquired) { return operation.get(); } else { throw new RuntimeException("获取锁失败"); } } finally { if (acquired) { lockService.releaseLock(lockKey, lockValue); } } }
public static void executeWithLock(RedisDistributedLock lockService, String lockKey, String lockValue, int expireTime, Runnable operation) { boolean acquired = false; try { acquired = lockService.acquireLock(lockKey, lockValue, expireTime); if (acquired) { operation.run(); } else { throw new RuntimeException("获取锁失败"); } } finally { if (acquired) { lockService.releaseLock(lockKey, lockValue); } } } } }
|