網站首頁 編程語言 正文
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
相關推薦
- 2022-07-28 C++中操作符的前置與后置有什么區別_C 語言
- 2022-07-03 TypeScript 變量聲明 —— 類型斷言
- 2022-10-05 虛擬機VMware?Tools安裝步驟_VMware
- 2022-04-06 關于Redis數據庫三種持久化方案介紹_Redis
- 2022-05-23 Jenkins實現集群化管理以及流水線項目配置_nginx
- 2022-03-14 idea中的子模塊無法新建class的解決方法(idea編譯沒有生成class文件)
- 2022-07-28 Redis特殊數據類型Geospatial地理空間_Redis
- 2021-12-02 docker容器時區錯誤問題_docker
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支