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=0spring.redis.host=127.0.0.1spring.redis.port=6379spring.redis.password=pwdspring.redis.timeout=0spring.redis.pool.max-active=8spring.redis.pool.max-idle=8spring.redis.pool.max-wait=-1spring.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切換成功