当前位置:网站首页>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
边栏推荐
猜你喜欢
【SSL集训DAY2】Sequence【数学】
ECCV 2022 | 微软开源TinyViT :搞定小模型的预训练能力
【SSL集训DAY2】Sort【树状数组】
ABAP中Collect的用法
Dry goods!Towards robust test-time adaptation
[Cloud Native] This article explains how to add Tencent Crane to Kubevela addon
Golden Warehouse Database KingbaseGIS User Manual (6.5. Geometry Object Editing Function)
Explore the TiDB Lightning source code to solve the found bugs
2022-08-09 mysql/stonedb-子查询性能提升-概论
高手这样看现货白银走势图
随机推荐
【集训DAY4】异或【字典树】
CAD 绘制圆角处理
【C语言】指针和数组的深入理解(第四期)
[Cloud Native] This article explains how to add Tencent Crane to Kubevela addon
直播app开发搭建,flutter 实现自适应、自动换行、相对布局
金仓数据库 KingbaseGIS 使用手册(6.5. 几何对象编辑函数)
ES6 从入门到精通 # 15:生成器 Generator 的用法
如何正则匹配乱码?
【诗歌】最高级的惩罚就是沉默
了解什么是架构基本概念和架构本质
伦敦银行情中短线的支撑和阻力位
Explore the TiDB Lightning source code to solve the found bugs
YOLOV5学习笔记(七)——训练自己数据集
【集训DAY5】快速排序【模拟】【数学】
基于ABP的AppUser对象扩展
In-depth understanding of multithreading (Part 1)
【诗歌】枕上诗书
上海一科技公司刷单被罚22万,揭露网络刷单灰色产业链
工程 (七) ——PolarSeg点云语义分割
技术盛宴!华云数据携六大议题亮相OpenInfra Days China