Spring boot 动态切换 Redis database

项目需要动态切换Redis database,在网上找了好久都是使用多个RedisTemplate,这种配置比较麻烦,自己研究测试使用一种简单的方法可以实现,性能方面未测试,请大家谅解。
在此之前需将Redis相关配置引入,我用的是Spring boot,需要 application.properties、RedisConfig.java这两个文件。相关配置网上很容易搜到。

如果上述文件均存在,可直接引入下面代码。

RedisUtils.java

主要代码如下:

@Resource
private RedisTemplate redisTemplate;

public void setDataBase(Integer index) {
		LettuceConnectionFactory redisConnectionFactory = (LettuceConnectionFactory)redisTemplate.getConnectionFactory();
		redisConnectionFactory.setDatabase(index);
		redisTemplate.setConnectionFactory(redisConnectionFactory);
}

系统调用:

@Autowired

private RedisUtils redisUtils;

redisUtils.setDataBase(4);

redisUtils.set("78-36-cc-44-af-29", tokenInfo,600);

Spring boot 动态切换 Redis database_第1张图片

 

你可能感兴趣的:(编程笔记)