javascript
SpringBoot如何切换Redis默认库
一些閑扯的話
我們清楚,Redis 盡管提供了 16 個(gè)索引庫(kù),但是每個(gè)數(shù)據(jù)庫(kù)之間是隔離互不共享的,客戶端默認(rèn)連接使用的是 0 號(hào)數(shù)據(jù)庫(kù) 。
注意:上方情況是基于單機(jī) Redis 的,在集群模式下是沒(méi)有多數(shù)據(jù)庫(kù)概念的,只有一個(gè) db0,不支持多 db。
所以,本文切換數(shù)據(jù)庫(kù)是基于單機(jī)版 Redis 的。
為什么 Redis 要有這么多的數(shù)據(jù)庫(kù),以及為啥要切換?
個(gè)人理解 ,Redis 之所以分這么多個(gè)數(shù)據(jù)庫(kù),也是為了區(qū)分業(yè)務(wù),不同的業(yè)務(wù)存放在不同的庫(kù),但是一個(gè) Redis,一般是給一個(gè)項(xiàng)目用,項(xiàng)目?jī)?nèi)的不同業(yè)務(wù),單獨(dú)用一個(gè)庫(kù),這樣不會(huì)相互有數(shù)據(jù)交叉。比如:用戶信息放到 0 庫(kù),商品數(shù)據(jù)放在 1 庫(kù)等等。
今天整理這篇文章是前段時(shí)間面試遇到了,然后整理了出來(lái),只是個(gè)思路,未提供動(dòng)態(tài)切換的工具類,好了廢話不多說(shuō)了,進(jìn)入正題吧。
方式一:配置文件方式
springboot的配置文件中提供了指定使用數(shù)據(jù)庫(kù)的屬性字段。
1、application.properties
spring.redis.database=0spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=1234
2、application.yml
spring??redis:
????host:?127.0.0.1
????port:?6379
????password:?1234
????database:?0
方式二:JedisConnectionFactory
JedisConnectionFactory 提供了 setDatabase() 方法來(lái)供我們指定使用的數(shù)據(jù)庫(kù)。
我們知道 Java 為我們提供了兩種 Redis 實(shí)現(xiàn)類:RedisTemplate 和 StringRedisTemplate;
本文以 StringRedisTemplate 為例,進(jìn)行 Redis 的 db 切換。
SpringBoot 1.X之前的版本
JedisConnectionFactory?jedisConnectionFactory?=?(JedisConnectionFactory)?stringRedisTemplate.getConnectionFactory();?jedisConnectionFactory.setDatabase(切換到指定的db上);
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
SpringBoot 2.X之后的版本
LettuceConnectionFactory?jedisConnectionFactory?=?(LettuceConnectionFactory)?redisTemplate.getConnectionFactory();jedisConnectionFactory.setDatabase(切換到指定的db上);
redisTemplate.setConnectionFactory(jedisConnectionFactory);
jedisConnectionFactory.resetConnection();
簡(jiǎn)單使用:
?private?StringRedisTemplate?redisTemplate;
?public?void?setDataBase(int?num)?{
????????LettuceConnectionFactory?connectionFactory?=?(LettuceConnectionFactory)?redisTemplate.getConnectionFactory();
????????if?(connectionFactory?!=?null?&&?num?!=?connectionFactory.getDatabase())?{
????????????connectionFactory.setDatabase(num);
????????????this.redisTemplate.setConnectionFactory(connectionFactory);
????????????connectionFactory.resetConnection();
????????}
}
面試:你們是如何切換Redis數(shù)據(jù)庫(kù)的?
一種參考回答,JedisConnectionFactory 提供了 setDatabase() 方法,可以通過(guò)該方法改變 Redis 使用的庫(kù)。
?
總結(jié)
以上是生活随笔為你收集整理的SpringBoot如何切换Redis默认库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [CSS] 点击事件触发的动画
- 下一篇: gradle idea java ssm