Springboot+Redis 同數(shù)據(jù)源動態(tài)切換db

本文參考:(Redis使用系列) Springboot 實(shí)現(xiàn)Redis 同數(shù)據(jù)源動態(tài)切換db 八
原文作者:小目標(biāo)青年

問題:平常使用的時候,redis的db是寫死的,如何去動態(tài)的修改呢?

image.png

解決辦法

  • 新建一個RedisDBChangeUtil.java
@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非常不友好?。ㄒ迷髡叩脑??)

測試一下:(版本:2.1.3.RELEASE)

  • 如果不是以上的版本的話,切換數(shù)據(jù)庫是沒有效果的,數(shù)據(jù)都會插入到默認(rèn)的db0中。
@RestController
@RequestMapping("/")
public class RedisStringController {
     @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisDBChangeUtil redisDBChangeUtil;

    @PostMapping("/changeDb")
    public String changeDb(){

       //默認(rèn)的插入
        stringRedisTemplate.opsForValue().set("name","db0");

        //插入db1
        redisDBChangeUtil.setDataBase(1);
        stringRedisTemplate.opsForValue().set("name1","db1");

        //插入db2
        redisDBChangeUtil.setDataBase(2);
        stringRedisTemplate.opsForValue().set("name2","db2");

        return  "ok";
    }
}
image.png

DB0

image.png

DB1

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容