springboot连接redis并动态切换database的实现⽅法
众所周知,redis多有个db,在jedis中可以使⽤select⽅法去动态的选择redis的database,但在springboot提供的StringRedisTemplate中确,没有该⽅法,好在StringRedisTemplate预留了⼀个setConnectionFactory⽅法,本⽂主为通过修改ConnectionFactory从⽽达到动态切换database的效果。
springboot连接redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
application.properties
#redis配置
TestCRedis.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class TestCRedis{
protected static Logger LOGGER = Logger(TestCRedis.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void t1(){
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
stringStringValueOperations.set("testkey","testvalue");
String testkey = ("testkey");
LOGGER.info(testkey);
}
}
运⾏TestCRedis.t1(),控制台打印“testvalue”redis连接成功
redis动态切换database
⾸先使⽤redis-cli,在redis的0、1、2三个库中,分别设置test 的值,分别为;0、1、2
TestCRedis.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class TestCRedis{
protected static Logger LOGGER = Logger(TestCRedis.class);
spring framework版本@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void t1(){
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
stringStringValueOperations.set("testkey","testvalue");
String testkey = ("testkey");
LOGGER.info(testkey);
}
public void t2() {
for (int i = 0; i <= 2; i++) {
JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) ConnectionFactory();
jedisConnectionFactory.setDatabase(i);
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
ValueOperations valueOperations = stringRedisTemplate.opsForValue();
String test = (String) ("test");
LOGGER.info(test);
}
}
运⾏TestCRedis.t2(),控制台分别打印 “0、1、2”,database切换成功
到此这篇关于springboot连接redis并动态切换database的⽂章就介绍到这了,更多相关springboot连接redis动态切换database 内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。