天天看點

SpringBoot如何切換Redis預設庫

一些閑扯的話

我們清楚,Redis 盡管提供了 16 個索引庫,但是每個資料庫之間是隔離互不共享的,用戶端預設連接配接使用的是 0 号資料庫 。

注意:上方情況是基于單機 Redis 的,在叢集模式下是沒有多資料庫概念的,隻有一個 db0,不支援多 db。

是以,本文切換資料庫是基于單機版 Redis 的。

為什麼 Redis 要有這麼多的資料庫,以及為啥要切換?

個人了解 ,Redis 之是以分這麼多個資料庫,也是為了區分業務,不同的業務存放在不同的庫,但是一個 Redis,一般是給一個項目用,項目内的不同業務,單獨用一個庫,這樣不會互相有資料交叉。比如:使用者資訊放到 0 庫,商品資料放在 1 庫等等。

今天整理這篇文章是前段時間面試遇到了,然後整理了出來,隻是個思路,未提供動态切換的工具類,好了廢話不多說了,進入正題吧。

方式一:配置檔案方式

springboot的配置檔案中提供了指定使用資料庫的屬性字段。

1、application.properties

spring.redis.database=0
spring.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() 方法來供我們指定使用的資料庫。

我們知道 Java 為我們提供了兩種 Redis 實作類:RedisTemplate 和 StringRedisTemplate;

本文以 StringRedisTemplate 為例,進行 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();
           

簡單使用:

 @Autowired
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資料庫的?

一種參考回答,JedisConnectionFactory 提供了 setDatabase() 方法,可以通過該方法改變 Redis 使用的庫。