Redis工具组件Lua脚本实现

复制代码
package com.jd.common.core.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
 * <p>Description: 分布式锁RedisLock</p>
 * <p>Copyright: Copyright (c)2,024</p>
 * <p>Company: tope</p>
 * <P>Created Date :2024年02月13日</P>
 * @version 1.0
 */
@Component
public class RedisLock {
    private final static Logger log = LoggerFactory.getLogger(RedisLock.class);
    @Autowired
    RedisTemplate redisTemplate;
    private StringRedisSerializer argsStringSerializer = new StringRedisSerializer();
    private StringRedisSerializer resultStringSerializer = new StringRedisSerializer();
    private final String EXEC_RESULT = "1";

    //定义获取锁的lua脚本
    private final static DefaultRedisScript<String> LOCK_LUA_SCRIPT = new DefaultRedisScript<>(
            "if redis.call('set',KEYS[1],ARGV[1],'NX','PX',ARGV[2]) then "
                    + "return '1' "
                    + "else "
                    + "return '0' "
                    + "end"
            , String.class
    );

    //定义释放锁的lua脚本
    private final static DefaultRedisScript<String> UNLOCK_LUA_SCRIPT = new DefaultRedisScript<>(
            "if redis.call('get',KEYS[1]) == ARGV[1] then "
                    + "return tostring(redis.call('del',KEYS[1])) "
                    + "else "
                    + "return '0' "
                    + "end"
            , String.class
    );

    /**
     * 加锁操作
     * @param key Redis 锁的 key 值
     * @param requestId 请求id,防止解了不该由自己解的锁 (随机生成)
     * @param expireTime 锁的超时时间(毫秒)
     * @param retryTimes 获取锁的重试次数
     * @return true or false
     */
    @SuppressWarnings("unchecked")
    public boolean lock(String key, String requestId, String expireTime, int retryTimes) {
        if (retryTimes <= 0) {
            retryTimes = 1;
        }
        try {
            int count = 0;
            while (true) {
                String result = (String) redisTemplate.execute(LOCK_LUA_SCRIPT, argsStringSerializer, resultStringSerializer,
                        Collections.singletonList(key), requestId, expireTime);
                log.debug("result:{},type:{}", result, result.getClass().getName());
                if (EXEC_RESULT.equals(result)) {
                    log.info("lock---->result:{},requestId:{}", "加锁成功", requestId);
                    return true;
                } else {
                    count++;
                    if (retryTimes == count) {
                        log.warn("has tried {} times , failed to acquire lock for key:{},requestId:{}", count, key, requestId);
                        return false;
                    } else {
                        log.warn("try to acquire lock {} times for key:{},requestId:{}", count, key, requestId);
                        Thread.sleep(100);
                        continue;
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("lock---->result:{},requestId:{}", "加锁异常", requestId);
        }
        return false;
    }

    /**
     * 解锁操作
     * @param key Redis 锁的 key 值
     * @param requestId 请求 id, 防止解了不该由自己解的锁 (随机生成)
     * @return true or false
     */
    @SuppressWarnings("unchecked")
    public boolean unLock(String key, String requestId) {
        String result = (String) redisTemplate.execute(UNLOCK_LUA_SCRIPT, argsStringSerializer, resultStringSerializer,
                Collections.singletonList(key), requestId);
        if (EXEC_RESULT.equals(result)) {
            log.info("unLock---->result:{},requestId:{}", "解锁成功", requestId);
            return true;
        }
        return false;
    }

}
相关推荐
麦聪聊数据13 分钟前
为何通用堡垒机无法在数据库运维中实现精准风控?
数据库·sql·安全·低代码·架构
2301_7903009618 分钟前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
m0_7369191034 分钟前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
亓才孓34 分钟前
[JDBC]PreparedStatement替代Statement
java·数据库
m0_466525291 小时前
绿盟科技风云卫AI安全能力平台成果重磅发布
大数据·数据库·人工智能·安全
爱学习的阿磊2 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
摇滚侠2 小时前
阿里云安装的 Redis 在什么位置,如何找到 Redis 的安装位置
redis·阿里云·云计算
枷锁—sha2 小时前
【SRC】SQL注入快速判定与应对策略(一)
网络·数据库·sql·安全·网络安全·系统安全
惜分飞2 小时前
ORA-600 kcratr_nab_less_than_odr和ORA-600 4193故障处理--惜分飞
数据库·oracle
chian-ocean2 小时前
CANN 生态进阶:利用 `profiling-tools` 优化模型性能
数据库·mysql