springboot连接redis并动态切换database的实现方法

网友投稿 557 2022-08-23


springboot连接redis并动态切换database的实现方法

众所周知,redis多有个db,在jedis中可以使用select方法去动态的选择redis的database,但在springboot提供的StringRedisTemplate中确,没有该方法,好在StringRedisTemplate预留了一个setConnectionFactory方法,本文主为通过修改ConnectionFactory从而达到动态切换database的效果。

springboot连接redis

pom.xml文件中引入spring-boot-starter-redis,版本可自行选择

org.springframework.boot

spring-boot-starter-redis

1.3.8.RELEASE

application.properties

#redis配置

spring.redis.database=0

spring.redis.host=127.0.0.1

spring.redis.port=6379

spring.redis.password=pwd

spring.redis.timeout=0

spring.redis.pool.max-active=8

spring.redis.pool.max-idle=8

spring.redis.pool.max-wagZowUBErZEit=-1

spring.redis.pool.min-idle=0

TestCRedis.java

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootgZowUBErZETest(classes = Application.class)

public class TestCRedis{

protected static Logger LOGGER = LoggerFactory.getLogger(TestCRedis.class);

@Autowired

private StringRedisTemplate stringRedisTemplate;

@Test

public void t1(){

ValueOperations stringStringValueOperations = stringRedisTemplate.opsForValue();

stringStringValueOperations.set("testkey","testvalue");

String testkey = stringStringValueOperations.get("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 = LoggerFactory.getLogger(TestCRedis.class);

@Autowired

private StringRedisTemplate stringRedisTemplate;

@Test

public void t1(){

ValueOperations stringStringValueOperations = stringRedisTemplate.opsForValue();

stringStringValueOperations.set("testkey","testvalue");

String testkey = stringStringValueOperations.get("testkey");

LOGGER.info(testkey);

}

public void t2() {

for (int i = 0; i <= 2; i++) {

JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();

jedisConnectionFactory.setDatabase(i);

stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);

ValueOperations valueOperations = stringRedisTemplate.opsForValue();

String test = (String) valueOperations.get("test");

LOGGER.info(test);

}

}

运行TestCRedis.t2(),控制台分别打印 “0、1、2”,database切换成功


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:极客编程python入门-流程控制3/7(python极客项目)
下一篇:KeyError: 'module_list.85.Conv2d.weight' #657
相关文章

 发表评论

暂时没有评论,来抢沙发吧~