SpringBoot如何切换Redis默认库

  • 2020 年 1 月 19 日
  • 筆記

一些闲扯的话

我们清楚,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 实现类:RedisTemplateStringRedisTemplate

本文以 StringRedisTemplate 为例,进行 Redisdb 切换。

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 使用的库。