springboot連接redis並動態切換database


 

摘自: https://blog.csdn.net/jlh912008548/article/details/78982008
【未實踐驗證】

springboot連接redis並動態切換database

眾所周知,redis多有個db,在jedis中可以使用select方法去動態的選擇redis的database,但在springboot提供的StringRedisTemplate中確,沒有該方法,好在StringRedisTemplate預留了一個setConnectionFactory方法,本文主為通過修改ConnectionFactory從而達到動態切換database的效果。

springboot連接redis

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

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.8.RELEASE</version> </dependency>

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-wait=-1 spring.redis.pool.min-idle=0

 

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<String, String> 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<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue(); stringStringValueOperations.set("testkey","testvalue"); String testkey = stringStringValueOperations.get("testkey"); LOGGER.info(testkey); } @Test 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切換成功


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM