public class RedisUtils {
private static final int timeout = 5000;
/**
* 加锁
* @param key redisKey
* @param expireTime 过期时间(秒)
* @param requestId 请求标识
* @return
*/
public static Boolean lock(String key, long expireTime, String requestId) {
long start = System.currentTimeMillis();
for (;;) {
boolean ret = SpringUtils.getBean(RedisCache.class).redisTemplate.opsForValue().setIfAbsent(key, requestId, expireTime, TimeUnit.SECONDS);
if (ret) {
return true;
}
long end = System.currentTimeMillis() - start;
if (end >= timeout) {
return false;
}
}
}
/**
* 释放锁
**/
public static Long releaseLock(String key, String requestId) {
String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class);
Long releaseStatus = (Long) SpringUtils.getBean(RedisCache.class).redisTemplate.execute(redisScript, Collections.singletonList(key), requestId);
return releaseStatus;
}
}
Redis锁工具类
最新推荐文章于 2024-04-22 15:06:23 发布