redis分布式秒杀锁

-- 获取锁标识,是否与当前线程一致?
if(redis.call('get', KEYS[1]) == ARGV[1]) then
    -- 一致,删除
    return redis.call('del', KEYS[1])
end
-- 不一致,直接返回
return 0
package com.platform.lock;

public interface ILock {

    /**
     * 获取锁
     * @param timeoutSec
     * @return
     */
    public boolean tryLock(long timeoutSec);

    /**
     * 锁标识、释放锁
     */
    public void unlock();
}
package com.platform.lock;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * redis的分布式锁
 * 实现ILock接口
 */
public class SimpleRedisLock implements ILock {

    // 不同的业务有不同的锁名称
    private String name;

    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "tryLock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    // DefaultRedisScript,
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 初始化 UNLOCK_SCRIPT,用静态代码块的方式,一加载SimpleRedisLock有会加载unlock.lua
    // 避免每次调unLock() 才去加载,提升性能!!!
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        // setLocation() 设置脚本位置
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        // 返回值类型
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /**
     * 获取锁
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取线程标示
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁
        // set lock thread1 nx ex 10
        // nx : setIfAbsent(如果不存在) , ex : timeoutSec(秒)
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        // 自动拆箱(Boolean -> boolean)!!!可能有风险
        return Boolean.TRUE.equals(success);
    }

    /**
     * 解决判断(锁标识、释放锁)这两个动作,之间产生阻塞!!!
     * JVM的 FULL GC
     * 要让这两个动作具有原子性
     */
    @Override
    public void unlock() {
        // 调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }
}
    @PostMapping("/cancelPublicBenefit")
    @CheckRepeatCommit
    public RestResponse cancelPublicBenefit(@LoginUser MallUserEntity loginUser, @RequestBody MallPublicBenefitEntity publicBenefitEntity) {

        String key = PUBLIC_BENEFIT_TEAM_LOCK_FLAG + publicBenefitEntity.getId();
        RestResponse restResponse = null;

        SimpleRedisLock simpleRedisLock = new SimpleRedisLock(key,stringRedisTemplate);
        try {
            if (simpleRedisLock.tryLock(15)) {
                // 成功获取锁,执行业务逻辑
                restResponse = mallPublicBenefitService.cancelPublicBenefit(loginUser, publicBenefitEntity);
            } else {
                // 获取锁失败,处理失败逻辑
                throw new BusinessException("服务器繁忙!");
            }
        } finally {
            simpleRedisLock.unlock();
        }

        return restResponse;
    }
相关推荐
小菜yh5 分钟前
关于Redis
java·数据库·spring boot·redis·spring·缓存
Microsoft Word25 分钟前
数据库系统原理(第一章 数据库概述)
数据库·oracle
问道飞鱼29 分钟前
分布式中间件-Pika一个高效的分布式缓存组件
分布式·缓存·中间件
华为云开源35 分钟前
openGemini 社区人才培养计划:助力成长,培养新一代云原生数据库人才
数据库·云原生·开源
小宋10212 小时前
玩转RabbitMQ声明队列交换机、消息转换器
服务器·分布式·rabbitmq
小安运维日记3 小时前
Linux云计算 |【第四阶段】NOSQL-DAY1
linux·运维·redis·sql·云计算·nosql
kejijianwen4 小时前
JdbcTemplate常用方法一览AG网页参数绑定与数据寻址实操
服务器·数据库·oracle
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
高兴就好(石7 小时前
DB-GPT部署和试用
数据库·gpt
这孩子叫逆7 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql