spring boot 同一個redis 操作不同的庫

1.下面是在Spring Boot中配置多個Redis數據庫的幾種方式:

1.1 配置如下
# application.yml
spring:redis:host: localhostport: 6379password: your_password# 連接池配置lettuce:pool:max-active: 8max-idle: 8min-idle: 0max-wait: -1mstimeout: 5000ms# 多個數據庫配置database0:database: 0  # 默認庫database1:database: 1  # 訂單庫database2:database: 2  # 用戶庫

2. Redis配置類

2.1代碼如下
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig {@Bean@Primarypublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {return createRedisTemplate(connectionFactory);}@Bean(name = "redisTemplate1")public RedisTemplate<String, Object> redisTemplate1(@Qualifier("redisConnectionFactory1") RedisConnectionFactory connectionFactory) {return createRedisTemplate(connectionFactory);}@Bean(name = "redisTemplate2")public RedisTemplate<String, Object> redisTemplate2(@Qualifier("redisConnectionFactory2") RedisConnectionFactory connectionFactory) {return createRedisTemplate(connectionFactory);}@Bean@Primarypublic RedisConnectionFactory redisConnectionFactory(@Value("${spring.redis.host}") String host,@Value("${spring.redis.port}") int port,@Value("${spring.redis.password}") String password,@Value("${spring.redis.database0.database}") int database) {return createConnectionFactory(host, port, password, database);}@Bean(name = "redisConnectionFactory1")public RedisConnectionFactory redisConnectionFactory1(@Value("${spring.redis.host}") String host,@Value("${spring.redis.port}") int port,@Value("${spring.redis.password}") String password,@Value("${spring.redis.database1.database}") int database) {return createConnectionFactory(host, port, password, database);}@Bean(name = "redisConnectionFactory2")public RedisConnectionFactory redisConnectionFactory2(@Value("${spring.redis.host}") String host,@Value("${spring.redis.port}") int port,@Value("${spring.redis.password}") String password,@Value("${spring.redis.database2.database}") int database) {return createConnectionFactory(host, port, password, database);}private RedisTemplate<String, Object> createRedisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);// 配置序列化器Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);mapper.registerModule(new JavaTimeModule());jsonSerializer.setObjectMapper(mapper);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(jsonSerializer);template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(jsonSerializer);template.afterPropertiesSet();return template;}private RedisConnectionFactory createConnectionFactory(String host, int port, String password, int database) {LettuceConnectionFactory factory = new LettuceConnectionFactory();factory.setHostName(host);factory.setPort(port);factory.setPassword(password);factory.setDatabase(database);// Lettuce連接池配置GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();poolConfig.setMaxTotal(8);poolConfig.setMaxIdle(8);poolConfig.setMinIdle(0);poolConfig.setMaxWaitMillis(-1);factory.afterPropertiesSet();return factory;}
}

3.Redis操作服務

3.1 代碼如下
@Service
@Slf4j
public class RedisService {@Autowired@Qualifier("redisTemplate")  // 默認庫private RedisTemplate<String, Object> redisTemplate;@Autowired@Qualifier("redisTemplate1")  // 訂單庫private RedisTemplate<String, Object> redisTemplate1;@Autowired@Qualifier("redisTemplate2")  // 用戶庫private RedisTemplate<String, Object> redisTemplate2;/*** 默認庫操作*/public void setDefault(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);} catch (Exception e) {log.error("Redis默認庫操作失敗: key={}", key, e);throw new RuntimeException("Redis操作失敗", e);}}/*** 訂單庫操作*/public void setOrder(String key, Object value) {try {redisTemplate1.opsForValue().set(key, value);} catch (Exception e) {log.error("Redis訂單庫操作失敗: key={}", key, e);throw new RuntimeException("Redis操作失敗", e);}}/*** 用戶庫操作*/public void setUser(String key, Object value) {try {redisTemplate2.opsForValue().set(key, value);} catch (Exception e) {log.error("Redis用戶庫操作失敗: key={}", key, e);throw new RuntimeException("Redis操作失敗", e);}}/*** 批量操作示例*/public void batchOperation() {try {// 使用管道批量處理redisTemplate.executePipelined(new SessionCallback<Object>() {@Overridepublic Object execute(RedisOperations operations) throws DataAccessException {operations.opsForValue().set("key1", "value1");operations.opsForValue().set("key2", "value2");return null;}});redisTemplate1.executePipelined(new SessionCallback<Object>() {@Overridepublic Object execute(RedisOperations operations) throws DataAccessException {operations.opsForValue().set("order1", "value1");operations.opsForValue().set("order2", "value2");return null;}});} catch (Exception e) {log.error("Redis批量操作失敗", e);throw new RuntimeException("Redis操作失敗", e);}}
}

4. 使用示例

4.1代碼如下
@RestController
@RequestMapping("/api/redis")
@Slf4j
public class RedisController {@Autowiredprivate RedisService redisService;@PostMapping("/default")public ResponseEntity<?> setDefault(@RequestParam String key, @RequestParam String value) {try {redisService.setDefault(key, value);return ResponseEntity.ok().build();} catch (Exception e) {log.error("設置默認庫失敗", e);return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("操作失敗");}}@PostMapping("/order")public ResponseEntity<?> setOrder(@RequestParam String key, @RequestParam String value) {try {redisService.setOrder(key, value);return ResponseEntity.ok().build();} catch (Exception e) {log.error("設置訂單庫失敗", e);return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("操作失敗");}}@PostMapping("/user")public ResponseEntity<?> setUser(@RequestParam String key, @RequestParam String value) {try {redisService.setUser(key, value);return ResponseEntity.ok().build();} catch (Exception e) {log.error("設置用戶庫失敗", e);return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("操作失敗");}}
}

5. 緩存配置(可選)

5.1 代碼如下
@Configuration
@EnableCaching
public class CacheConfig {@Beanpublic CacheManager cacheManager(RedisConnectionFactory connectionFactory) {// 創建多個緩存管理器Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();// 默認緩存配置cacheConfigs.put("default", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));// 訂單緩存配置cacheConfigs.put("order", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)));// 用戶緩存配置cacheConfigs.put("user", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(2)));return RedisCacheManager.builder(connectionFactory).cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()).withInitialCacheConfigurations(cacheConfigs).build();}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/62450.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/62450.shtml
英文地址,請注明出處:http://en.pswp.cn/web/62450.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C語言面試題/筆試題/高頻面試題_2

9. 全局變量和局部變量的區別 定義&#xff1a;全局變量是定義在函數外部的變量&#xff0c;局部變量是定義在 函數內部的變量 存儲位置&#xff1a;全局變量存儲在全局區&#xff0c;局部變量存儲在棧區 作用域&#xff1a;全局變量可以在程序任意位置使用&#xff0c;局部變量…

Brain.js(八):RNNTimeStep 實戰教程 - 股票價格預測 - 實操需警慎

前置聲明&#xff0c;個人淺度炒股&#xff0c;但計劃將基金轉入股市。然后 股市有風險&#xff0c;不是技術可以完全預測的&#xff0c;但是在無頭緒的時候&#xff0c;用技術指標做個參考也不錯。 本文涉及到的股票預測&#xff0c;只是代碼簡單示例&#xff0c;實操需警慎&a…

MySQL | 尚硅谷 | 第13章_約束

MySQL筆記&#xff1a;第13章_約束 文章目錄 MySQL筆記&#xff1a;第13章_約束第13章_約束 1. 約束(constraint)概述1.1 為什么需要約束1.2 什么是約束1.3 約束的分類演示代碼 2. 非空約束2.1 作用2.2 關鍵字2.3 特點2.4 添加非空約束2.5 刪除非空約束演示代碼 3. 唯一性約束3…

《計算機網絡》(408大題)

2009 路由轉發和靜態路由的計算 子網劃分、路由聚合的計算 注&#xff1a;CIDR中的子網號可以全為0或1&#xff0c;但是其主機號不允許。 注&#xff1a; 這里其實是把到互聯網的路由當做了一個默認路由&#xff08;當一個目的網絡地址與路由表中其他都不匹配時&#xff0c;…

NanoLog起步筆記-6-StaticLogInfo

nonolog起步筆記-6-StaticLogInfo StaticLogInfo文件名和行號文件名和行號的傳入log參數 RuntimeLogger::registerInvocationSitelogid為什么只能被賦一次值 reserveAlloc加入消息頭finishAlloc返回 StaticLogInfo 寫C語言編譯前端時&#xff0c;給我印象深刻的一部分是&#…

軟件工程 概述

軟件 不僅僅是一個程序代碼。程序是一個可執行的代碼&#xff0c;它提供了一些計算的目的。 軟件被認為是集合可執行的程序代碼&#xff0c;相關庫和文檔的軟件。當滿足一個特定的要求&#xff0c;就被稱為軟件產品。 工程 是所有有關開發的產品&#xff0c;使用良好定義的&…

Sui 集成 Phantom,生態迎來全新里程碑

作為領先的非托管多鏈加密&#x1f45b;&#xff0c;Phantom 宣布將支持 Sui 區塊鏈。Sui 將加入 Solana、Bitcoin 和 Ethereum 隊伍&#xff0c;成為該 wallet 支持的少數 L1 區塊鏈之一。 此次集成也大幅提升了 Phantom 的互操作性&#xff0c;同時表明 wallet 提供商和應用…

目標跟蹤領域經典論文解析

親愛的小伙伴們&#x1f618;&#xff0c;在求知的漫漫旅途中&#xff0c;若你對深度學習的奧秘、JAVA 、PYTHON與SAP 的奇妙世界&#xff0c;亦或是讀研論文的撰寫攻略有所探尋&#x1f9d0;&#xff0c;那不妨給我一個小小的關注吧&#x1f970;。我會精心籌備&#xff0c;在…

如何解決 java.nio.charset.CoderMalfunctionError: 編碼器故障錯誤問題?親測有效的解決方法!

java.nio.charset.CoderMalfunctionError 是一個在 Java 中相對較少遇到的異常&#xff0c;通常與字符編碼轉換過程中的錯誤有關。當 Java 程序在進行字符編碼轉換時&#xff0c;遇到無法處理的字符或編碼故障時&#xff0c;就會拋出該異常。 1. 問題描述 java.nio.charset.C…

低級爬蟲實現-記錄HCIP云架構考試

因工作需要考HCIP云架構&#xff08;HCIP-Cloud Service Solution Architect&#xff09;證書, 特意在淘寶上買了題庫&#xff0c; 考過了。 事后得知自己被坑了&#xff0c; 多花了幾十大洋。 所以想著在授權期內將題庫“爬”下來&#xff0c; 共享給大家。 因為整個過程蠻有…

QGroundControl之5-AppSettings.cc

介紹 應用程序設置 Application Settings &#xff0c;這里看下語言選擇功能&#xff0c;它是怎么和json文件關聯起來的&#xff0c;剛剛看的時候&#xff0c;很是奇怪這么多的json文件作用。 1.AppSettings.cc 文件怎么和App.SettingsGroup.json關聯 在AppSettings.cc文件沒…

jenkins郵件的配置詳解

Jenkins郵件的配置涉及多個步驟和細節,以下是詳細的配置指南: 一、前期準備 確定郵件服務:明確Jenkins將要使用的郵件服務,如QQ郵箱、163郵箱、公司郵箱(基于Microsoft 365或Exchange Server)等。獲取SMTP配置信息:根據郵件服務類型,獲取相應的SMTP服務器地址、端口號…

【ArcGIS微課1000例】0134:ArcGIS Earth實現二維建筑物的三維完美顯示

文章目錄 一、加載數據二、三維顯示三、三維符號化一、加載數據 加載配套實驗數據(0134.rar中的建筑物,2d或3d都可以),方法如下:點擊添加按鈕。 點擊【Add Files】,在彈出的Open對話框中,選擇建筑物,點擊確定,完成添加。 默認二維顯示: 二、三維顯示 右鍵建筑物圖層…

jupyterlab 增加多個kernel,正確做法

1、背景 需要增加一個kernel然后相當于隔離一個環境 juypterlab Version 3.0.14 2、用conda 安裝 例如&#xff0c;你在conda下有一個python 3.12 的環境 py312 ipython kernel install --user --namepy312 如果保持的話&#xff0c;用pip安裝相應的包就好 3、檢查是否配置好 …

案例-商品列表(組件封裝)

標簽組件封裝 1.雙擊顯示&#xff0c;自動聚焦 2.失去焦點&#xff0c;隱藏輸入框 標簽一列&#xff0c;不同行的標簽內容不同&#xff0c;但是除此之外其他基本一致&#xff0c;所以選擇用 標簽組件 將這一部分封裝為一個組件&#xff0c;需要時組件標簽展示。 首先標簽處一進…

Python 基礎學習(一)

一.基礎語法 注釋 Python中單行注釋以 # 開頭&#xff0c;如下&#xff1a; #!/usr/bin/python3# 第一個注釋 print ("Hello, Python!") # 第二個注釋多行注釋可以用多個 # 號&#xff0c;還有 ‘’’ 和 “”"&#xff1a; #!/usr/bin/python3# 第一個注釋…

TIM輸入捕獲---STM

一、簡介 IC輸入捕獲 輸入捕獲模式下&#xff0c;當通道輸入引腳出現指定電平跳變時&#xff0c;當前CNT的值將被鎖存在CCR中&#xff0c;可用于測量PWM波形的頻率、占空比、脈沖間隔、電平持續時間等參數 每個高級定時器和通用定時器都擁有4個輸入捕獲通道 可配置為PWMI模…

【Android Studio】學習——網絡連接

實驗&#xff1a;Android網絡連接 文章目錄 實驗&#xff1a;Android網絡連接[toc]實驗目標和實驗內容&#xff1a;1、掌握Android聯網的基本概念&#xff1b;2、能夠使用URL connection實現網絡連接&#xff1b;3、掌握第三方庫的基本概念4、需實現的具體功能 實驗結果功能說明…

ROS學習筆記二:ROS環境搭建

安裝ubuntu安裝ROS 參考趙虛左老師教程&#xff1a;ROS安裝ROS 快速上手體驗 -使用命令來實現 –創建工作空間&#xff1a; mkdir -p ros_learn_ws/src// ros_learn_ws為自定義空間 cd ros_learn_ws catkin_make –創建ROS功能包并添加依賴 cd src catkin_create_pkg demo_01 r…

5G中什么是ATG網絡?

有人問Air to Ground Networks for NR是怎么回事&#xff1f;這個是R18 NR才引入的。 ATG很多部分和NTN類似中的內容類似。比較明顯不同的是&#xff0c;NTN的RF內容有TS 38.101-5單獨去講&#xff0c;而ATG則會和地面網絡共用某些band&#xff0c;ATG可以工作在N1/N3/N34/N39…