springbootはredisを接続して、動的にdatabaseを切り替えます。


springbootはredisを接続して、動的にdatabaseを切り替えます。
よく知られているように、redisには多くのdbがあり、ject方法でredisのdatabaseを動的に選択することができますが、springbootで提供されたStringRedis Templateでは、この方法はありません。StringRedis TemplateにはsetConnection Factory方法が予約されています。
springboot接続redis
pom.xmlファイルにspring-book-starter-redisを導入して、バージョンは自分で選択できます。
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-redisartifactId>
    <version>1.3.8.RELEASEversion>
dependency>
appication.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 stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set("testkey","testvalue");
        String testkey = stringStringValueOperations.get("testkey");
        LOGGER.info(testkey);
    }

}
TestCRedis.t 1()を実行し、コンソールプリント「testvalue」redis接続に成功しました。
redisダイナミック切り替えdatabase
まずredis-cliを使って、redisの0、1、2の3つの倉庫の中で、それぞれ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);
    }

    @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.t 2()を実行して、コンソールはそれぞれ“0、1、2”を印刷して、databaseは切り替えに成功しました。