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