当前位置:网站首页>redis distributed lock code example
redis distributed lock code example
2022-08-10 00:56:00 【shy_snow】
import java.util.Collections;
import redis.clients.jedis.Jedis;
public class RedisTool
{
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";
/** * 尝试获取分布式锁 * * @param jedis Redis客户端 * @param lockKey 锁 * @param requestId 请求标识 * @param expireTime 超期时间 * @return 是否获取成功 */
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime)
{
/* * set(String key, String value, String nxxx, String expx, int time) * 第一个为key,我们使用key来当锁,因为key是唯一的. * 第二个为value,我们传的是requestId,很多童鞋可能不明白,有key作为锁不就够了吗,为什么还要用到value?原因就是我们在上面讲到可靠性时,分布式锁要满足第四个条件解铃还须系铃人, * 通过给value赋值为requestId,我们就知道这把锁是哪个请求加的了,在解锁的时候就可以有依据.requestId可以使用UUID.randomUUID().toString()方法生成. * 第三个为nxxx,这个参数我们填的是NX,意思是SET IF NOT EXIST,即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作; * 第四个为expx,这个参数我们传的是PX,意思是我们要给这个key加一个过期的设置,具体时间由第五个参数决定. 第五个为time,与第四个参数相呼应,代表key的过期时间,单位为ms. * 总的来说,执行set()方法就只会导致两种结果: 1. 当前没有锁(key不存在),那么就进行加锁操作,并对锁设置个有效期,同时value表示加锁的客户端. 2. 已有锁存在,不做任何操作. */
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result))
{
return true;
}
return false;
}
private static final Long RELEASE_SUCCESS = 1L;
/** * 释放分布式锁 * @param jedis Redis客户端 * @param lockKey 锁 * @param requestId 请求标识 * @return 是否释放成功 */
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
// 使用lua脚本保证原子性
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;
}
public static void main(String[] args) {
String host = "192.168.129.124";
int port = 6379;
Jedis jedis = new Jedis(host,port);
String lockKey = "lockKey";
boolean ret = tryGetDistributedLock(jedis, lockKey, "requestId", 5000);
System.out.println(ret+", "+jedis.get(lockKey));
ret = releaseDistributedLock(jedis, lockKey, "requestId2");
ret = tryGetDistributedLock(jedis, lockKey, "requestId2", 5000);
System.out.println(ret+", "+jedis.get(lockKey));
ret = releaseDistributedLock(jedis, lockKey, "requestId");
System.out.println(ret+", "+jedis.get(lockKey));
ret = tryGetDistributedLock(jedis, lockKey, "requestId2", 5000);
System.out.println(ret+", "+jedis.get(lockKey));
}
}
https://www.w3cschool.cn/redis/redis-yj3f2p0c.html
边栏推荐
猜你喜欢
随机推荐
Click: 518. Change Exchange II
Explore the TiDB Lightning source code to solve the found bugs
金仓数据库 KingbaseGIS 使用手册(6.2. 管理函数)
A Shanghai technology company was fined 220,000 for brushing orders, exposing the gray industry chain of online brushing
【诗歌】最高级的惩罚就是沉默
Live Preview | ICML 2022 11 first-author scholars share online neural network, graph learning and other cutting-edge research
力扣:518. 零钱兑换 II
JSON对象和字符串相互转化
conda新建环境时报错NotWritableError: The current user does not have write permissions
用哈希简单封装unordered_map和unordered_set
Eureka自我保护
[Cloud Native] This article explains how to add Tencent Crane to Kubevela addon
2021年国内外五大BI厂商——优秀的商业智能工具推荐
领跑政务云,连续五年中国第一
伦敦银行情中短线的支撑和阻力位
干货!迈向鲁棒的测试时间适应
Golden Warehouse Database KingbaseGIS User Manual (6.5. Geometry Object Editing Function)
68. qt quick-qml multi-level folding drop-down navigation menu supports dynamic add/unload, support qml/widget loading, etc.
金仓数据库 KingbaseGIS 使用手册(6.3. 几何对象创建函数)
Filament-Material 绘制基本图形