java代码redis分布式锁代码
时间: 2023-02-24 12:21:04 浏览: 189
redis实现分布式锁(java/jedis)
以下是一份 Java 代码实现 Redis 分布式锁的示例:
```
import redis.clients.jedis.Jedis;
import java.util.Collections;
public class RedisDistributedLock {
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final Long RELEASE_SUCCESS = 1L;
/**
* 尝试获取分布式锁
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间
* @return 是否获取成功
*/
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
* 释放分布式锁
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
}
```
使用示例:
```
Jedis jedis = new Jedis("localhost");
String lockKey = "lockKey";
String requestId = String.valueOf(System.currentTimeMillis());
if (RedisDistributedLock.tryGetDistributedLock(jedis, lockKey, requestId, 10000)) {
try {
// do something
} finally {
RedisDistributedLock.releaseDistributedLock(jedis, lockKey, requestId);
}
}
```
请注意,这仅仅是一个简单的 Redis 分布式锁的示例代码
阅读全文