redis实现分布式锁java代码
时间: 2023-08-25 19:05:42 浏览: 131
详解Java如何实现基于Redis的分布式锁
以下是一个基于Redis实现分布式锁的Java代码示例:
```java
import redis.clients.jedis.Jedis;
public class DistributedLock {
private final Jedis jedis;
public DistributedLock(Jedis jedis) {
this.jedis = jedis;
}
/**
* 尝试获取锁
*
* @param lockKey 锁的key
* @param requestId 请求标识,用于解锁
* @param expire 锁的过期时间,单位:秒
* @return 是否获取成功
*/
public boolean tryLock(String lockKey, String requestId, int expire) {
String result = jedis.set(lockKey, requestId, "NX", "EX", expire);
return "OK".equals(result);
}
/**
* 释放锁
*
* @param lockKey 锁的key
* @param requestId 请求标识
* @return 是否释放成功
*/
public boolean releaseLock(String lockKey, String requestId) {
String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(luaScript, 1, lockKey, requestId);
return "OK".equals(result);
}
}
```
使用示例:
```java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class DistributedLockTest {
public static void main(String[] args) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(10);
poolConfig.setMaxIdle(5);
poolConfig.setMinIdle(1);
JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379, 1000, null);
Jedis jedis = jedisPool.getResource();
DistributedLock lock = new DistributedLock(jedis);
String lockKey = "test_lock";
String requestId = "test_request";
int expire = 10;
// 尝试获取锁
boolean success = lock.tryLock(lockKey, requestId, expire);
if (success) {
System.out.println("获取锁成功");
// do something
// 释放锁
boolean released = lock.releaseLock(lockKey, requestId);
if (released) {
System.out.println("释放锁成功");
} else {
System.out.println("释放锁失败");
}
} else {
System.out.println("获取锁失败");
}
jedis.close();
jedisPool.close();
}
}
```
需要注意的是,在释放锁的时候需要使用Redis的`eval`命令执行Lua脚本来保证原子性。在Lua脚本中,先判断锁的值是否为当前请求标识,如果是则删除锁并返回1,否则返回0。在Java代码中,如果`releaseLock`方法返回true,则表示释放锁成功。
阅读全文