CountDownLatch模拟多线程使用Redisson实现秒杀扣减库存

1.不加锁版本

	@Test
    public void testLock1() {
        // 从redis获取库存数量
        int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get("stock")));
        // 如果库存数量大于0
        if (stock > 0) {
            int realStock = stock -1;
            redisTemplate.opsForValue().set("stock", realStock + "");
            System.out.println("扣减成功,剩余库存:" + realStock);
        } else { // 如果库存数量小于0
            System.out.println("扣减失败,库存不足!");
        }

    }

用的是springbootTest进行模拟的普通秒杀扣减库存,从redis扣减库存

1.1测试代码

	@Test
    public void testLock() throws InterruptedException {
        redisTemplate.opsForValue().set("stock", 100 + "");
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        ExecutorService executor = Executors.newFixedThreadPool(1000);
        for(int i = 0; i < 1000; i++) {
            executor.execute(() -> {
                try {
                    testLock1();
                } catch (Exception e) {
                    log.error("异常", e);
                } finally {
                    countDownLatch.countDown();
                }
            });

        }
        // 等待所有线程执行完毕
        countDownLatch.await();
        // 关闭线程池
        executor.shutdown();
        int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get("stock")));
        System.err.println("::::::剩余库存:::::::" +stock);
    }

在这里插入图片描述可以看到执行了1000次还显示库存是96呢,因为多个线程去查redis的时候可能都是100,然后都执行100-1,他同时变成99,导致数据错误;

1.2使用Redisson枷锁的方式

	@Test
    public void testLock2() {
        String lockKey = "lockKey";
        // 获取到redisson锁对象
        RLock redissonLock = redissonClient.getLock(lockKey);
        try {
            redissonLock.lock();
            // 从redis获取库存数量
            int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get("stock")));
            // 如果库存数量大于0
            if (stock > 0) {
                int realStock = stock -1;
                redisTemplate.opsForValue().set("stock", realStock + "");
                System.out.println("扣减成功,剩余库存:" + realStock);
            } else { // 如果库存数量小于0
                System.out.println("扣减失败,库存不足!");
            }

        } finally { // 防止异常导致锁无法释放!!!
            redissonLock.unlock();
        }

    }

需要配置redisson客户端和引入redisson依赖才能用哦!!!
测试代码

	@Test
    public void testLock() throws InterruptedException {
        redisTemplate.opsForValue().set("stock", 100 + "");
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        ExecutorService executor = Executors.newFixedThreadPool(1000);
        for(int i = 0; i < 1000; i++) {
            executor.execute(() -> {
                try {
                    testLock2();
                } catch (Exception e) {
                    log.error("异常", e);
                } finally {
                    countDownLatch.countDown();
                }
            });

        }
        // 等待所有线程执行完毕
        countDownLatch.await();
        // 关闭线程池
        executor.shutdown();
        int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get("stock")));
        System.err.println("::::::剩余库存:::::::" +stock);
    }

在这里插入图片描述

在这里插入图片描述

非常优雅的执行完毕把库存扣减为0

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值