用redis分布式锁+lua实现库存量的减少

本文介绍了一种使用Redis实现的分布式锁方案,详细展示了如何通过Lua脚本来确保在高并发环境下库存变更操作的原子性和一致性。该方案适用于如优惠券发放等场景,能够有效防止超卖现象,保障业务流程的正确执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近来需要做一个优惠券的功能,因优惠券是有数量限制的,所以想到了用redis的分布式锁来实现库存的变更,当然,也可以用到商品的库存变更。

首先,为了确保分布式锁可用,我们至少要确保锁的实现同时满足以下四个条件:

  1. 互斥性。在任意时刻,只有一个客户端能持有锁。
  2. 不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
  3. 具有容错性。只要大部分的Redis节点正常运行,客户端就可以加锁和解锁。
  4. 加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。

下面是redis分布式锁的工具类

@Component
public class RedisLock {
    private Logger logger = LoggerFactory.getLogger(RedisLock.class);

    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;

    private static final String RELEASE_SUCCESS = "1";

    private static final String UNLOCK_LUA;
    private static final String LOCK_LUA;

    static {
        StringBuilder sb = new StringBuilder();
        sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] then");
        sb.append("    return tostring(redis.call(\"del\",KEYS[1])) ");
        sb.append("else ");
        sb.append("    return \"0\" ");
        sb.append("end ");
        UNLOCK_LUA = sb.toString();
    }

    static {
        StringBuilder sb = new StringBuilder();
        sb.append("if redis.call(\"set\",KEYS[1],ARGV[1],\"NX\",\"PX\",ARGV[2])");
        sb.append("then ");
        sb.append("    return \"1\" ");
        sb.append("else ");
        sb.append("    return \"0\" ");
        sb.append("end ");
        LOCK_LUA = sb.toString();
    }

    private static final StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    //private StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();

    /**
     * 上锁
     */
    public boolean lock(String key, String requestId, int retryTimes, String expireTime) {
        if (retryTimes <= 0)
            retryTimes = 1;

        try {
            int count = 0;
            while (true) {
                // 执行set命令
                DefaultRedisScript<String> stringDefaultRedisScript = lockRedisScript();
                String absent = redisTemplate.execute(stringDefaultRedisScript, stringRedisSerializer, stringRedisSerializer, Collections.singletonList(key), requestId, expireTime);
                //是否成功获取锁
                if (RELEASE_SUCCESS.equals(String.valueOf(absent))) {
                    return true;
                } else {
                    count++;
                    if (retryTimes == count) {
                        logger.warn("has tried {} times , failed to acquire lock for key:{},requestId:{}", count, key, requestId);
                        return false;
                    } else {
                        logger.warn("try to acquire lock {} times for key:{},requestId:{}", count, key, requestId);
                        Thread.sleep(100);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 解锁
     */
    public boolean unlock(String key, String requestId) {
        //使用Lua脚本:先判断是否是自己设置的锁,再执行删除
        DefaultRedisScript<String> stringDefaultRedisScript = unLockRedisScript();
        String result = redisTemplate.execute(stringDefaultRedisScript, stringRedisSerializer, stringRedisSerializer, Collections.singletonList(key), requestId);
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }


    @Bean
    public DefaultRedisScript<String> unLockRedisScript() {
        DefaultRedisScript<String> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(String.class);
        defaultRedisScript.setScriptText(UNLOCK_LUA);
//      defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("delete.lua")));
        return defaultRedisScript;
    }

    @Bean
    public DefaultRedisScript<String> lockRedisScript() {
        DefaultRedisScript<String> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(String.class);
        defaultRedisScript.setScriptText(LOCK_LUA);
//      defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("delete.lua")));
        return defaultRedisScript;
    }
}

业务中的实现逻辑

Object sto = redisCacheUtil.getCacheObject(CouponConstant.REDIS_COUPON_STOCK + userCouponDto.getfCouponId().toString());
Integer stoNum;
if (!StringUtils.isEmpty(sto)) {
    stoNum = Integer.parseInt(sto.toString());
} else {
    //获取当前优惠券剩余数
    stoNum = couponBean.getfGrantNum() - couponBean.getfIssuedNum();
    redisCacheUtil.setCacheObject(CouponConstant.REDIS_COUPON_STOCK + userCouponDto.getfCouponId().toString(), stoNum + "", 30L);
}
String requestId = UUID.randomUUID().toString();
if (stoNum > 0) {
    while (true) { //这里循环操作,以确保该线程一定获得锁并执行线程任务
        int retryTimes = 3; //重试次数
        String expireTime = "1000"; //过期时间
        if (redisLock.lock(CouponConstant.REDIS_COUPON_LOCK + userCouponDto.getfCouponId().toString(), requestId, retryTimes, expireTime)) {
            try {  //加其为避免库存超量
                stoNum--;
                CouponBean coupon = new CouponBean();
                coupon.setfId(userCouponBean.getfCouponId());
                coupon.setfIssuedNum(couponBean.getfGrantNum() - stoNum);
                int j = couponService.updateByPrimaryKeySelective(coupon);
                if (j != 0) {
                    redisCacheUtil.setCacheObject(CouponConstant.REDIS_COUPON_STOCK + userCouponDto.getfCouponId().toString(), stoNum + "", 30L);
                }
            } finally {
                boolean unlock = redisLock.unlock(CouponConstant.REDIS_COUPON_LOCK+userCouponDto.getfCouponId().toString(), requestId);
                if (unlock) {
                    logger.info("-------解锁成功-----");
                }
            }
            break;
        }
    }
}

在用多线程的测试中,测试成功

@GetMapping(value = "/testLock")
public void testLock() {
    UserCouponDto userCouponBean = new UserCouponDto();
    long l = System.currentTimeMillis();
    for (int i = 0; i < 1000; i++) {
        Thread thread = new Thread(() -> {
            userCouponBean.setfCouponId(1L);
            Map<String, Object> map = ShopCouponReceive(userCouponBean);
        });
        thread.run();
    }
    System.out.println("------------costTime" + (System.currentTimeMillis() - l));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值