默認redis使用的是db 0,而我們自己在配置連接的時候可以設置默認使用db ,如:
那麼怎麼去實現動態 去切換自己想使用的db呢?
先回顧性我們在配置redis的時候,連接redis使用的代碼段(舉例StirngRedisTemplate):
那麼切換也是同理,就是傳入factory的時候,設置好選擇的db:
新建RedisDBChangeUtil.java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
/**
* @Author : JCccc
* @CreateTime : 2020/4/21
* @Description :
**/
@Component
public class RedisDBChangeUtil {
@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();
}
}
}
注意!!!
注意!!!
注意!!!
注意!!!
LettuceConnectionFactory 是 在springboot 2.X版本使用,
但是
springboot 版本 spring-boot-starter-data-redis 的版本對這個redis切換db非常不友好!
親測 ,使用 springboot 2.1.3.RELEASE springboot 2.1.4.RELEASE springboot 2.1.5.RELEASE 可以成功切換。
但是從springboot 2.1.6.RELEASE 開始 到springboot 2.2.0.RELEASE 都是有問題的。
ok,最後簡單的切換使用演示:
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
RedisDBChangeUtil redisDBChangeUtil;
@ResponseBody
@RequestMapping("/addRedis")
public String addRedis() {
redisDBChangeUtil.setDataBase(2);
stringRedisTemplate.opsForValue().set("add to 2", "2020-06-02");
redisDBChangeUtil.setDataBase(3);
stringRedisTemplate.opsForValue().set("add to 3", "2020-06-02");
redisDBChangeUtil.setDataBase(1);
stringRedisTemplate.opsForValue().set("add to 1", "2020-06-02");
return "添加成功";
}
調用接口,可以看到redis裏面的值已經分別插入了:
ok,該篇教程就暫且到此結束。