日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

redis保存AtomicInteger對象踩坑及解決_Redis

作者:夜月如水 ? 更新時間: 2022-12-21 編程語言

redis保存AtomicInteger對象踩坑

redisTemplate 保存AtomicInteger對象異常:

java.lang.ClassCastException: java.util.concurrent.atomic.AtomicInteger cannot be cast to java.lang.String
?? ?at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:36)
?? ?at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:127)
?? ?at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:235)
?? ?at com.quan.starter.service.impl.RedisServiceImpl.set(RedisServiceImpl.java:139)

跟蹤源碼發現其執行的是 StringRedisSerializer 的實現,serialize默認接收的參數類型為String 從而拋出以上異常

經過檢查,發現是RedisTemplate泛型惹的禍:

@Autowired
private RedisTemplate<String, String> redisTemplate;

解決方案

去除泛型:

@Autowired
private RedisTemplate redisTemplate;

運行服務再次跟蹤源碼,執行的是 DefaultValueOperations 的實現,問題解決

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

原文鏈接:https://blog.csdn.net/w_quan/article/details/105137090

欄目分類
最近更新