RedisAtomicInteger 的使用

RedisAtomicInteger 的使用

RedisAtomicInteger 从名字上来说就是 redis 的原子Integer 数据类型,由于其原子性,, 可用于秒杀活动物品数量的控制。

以及保证顺序生成数字。

  @Resource
    RedisTemplate<String, Object> redisTemplate;


    /**
     * RedisAtomicInteger
     *
     * @throws Exception 异常
     */
    @Test
    public void testTransaction1() throws Exception {
        RedisAtomicInteger redisCount = new RedisAtomicInteger("key1", this.redisTemplate.getConnectionFactory());
        redisCount.set(0);
        // 创建 100 个线程 并发执行  increment 操作
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100; i++) {
            pool.submit(() -> {
                // 配额码原子变量值增加,每次增加1
                for (int j = 0; j < 100; j++) {
                    int count = redisCount.incrementAndGet();
                    log.info(Thread.currentThread().getName() + ": " + count);
                }
            });
        }
    }

结果
.
.
.
pool-2-thread-90: 9989
pool-2-thread-61: 9987
pool-2-thread-3: 9986
pool-2-thread-12: 9990
pool-2-thread-25: 9991
pool-2-thread-90: 9992
pool-2-thread-12: 9994
pool-2-thread-61: 9993
pool-2-thread-25: 9995
pool-2-thread-61: 10000
pool-2-thread-12: 9996
pool-2-thread-61: 9997
pool-2-thread-25: 9998
pool-2-thread-12: 9999

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值