package com.paic.phucp.console.djss;

import com.paic.phucp.common.utils.RedisUtil;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import java.util.Collections;

/**
 * 第一个为key,我们使用key来当锁名
 * 第二个为value,传的是uid,唯一随机数,也可以使用本机mac地址 + uuid
 * 第三个为NX,意思是SET IF NOT EXIST,即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作 
 * 第四个为PX,意思是我们要给这个key加一个过期的设置,具体时间由第五个参数决定 第五个为time,代表key的过期时间,对应第四个参数
PX毫秒,EX秒
 * */
@Component
public class LockImpl {

    public boolean lock(String lockId, String lockValue, int timeoutInSeconds)
{
        JedisCluster jedisCluster = RedisUtil.getJedisCluster();
        String result = jedisCluster.set(lockId, lockValue, "NX", "EX",
timeoutInSeconds);
        return "OK".equals(result);

    }

    public boolean unlock(String lockId, String lockValue) {
        JedisCluster jedisCluster = RedisUtil.getJedisCluster();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return
redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedisCluster.eval(script,
Collections.singletonList(lockId), Collections.singletonList(lockValue));
        return (result instanceof Long) && ((Long) result).longValue() == 1;
    }
}
 

技术
今日推荐
PPT
阅读数 119
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信