Springboot Connect Redis and dynamically switch database
As we all know, Redis has a db, in the Jedis can use the Select method to dynamically select the Redis database, but in the stringredistemplate provided by Springboot does not have this method, Fortunately, stringredistemplate reserved a setconnectionfactory method, this article is to modify the connectionfactory so as to achieve dynamic switching database effect. springboot Connection Redis
Pom.xml file to introduce Spring-boot-starter-redis, version can choose
<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);
}
Run Testcredis.t1 (), console print "TestValue" Redis connection successful redis dynamic switch Database
First, use REDIS-CLI to set the value of test in the 0, 1, 23 libraries of Redis, respectively 0, 1, 2
Testcredis.java
@RunWith (Springjunit4classrunner.class) @SpringBootTest (classes = application.class) public class testcredis{protect
ed static Logger Logger = Loggerfactory.getlogger (Testcredis.class);
@Autowired private Stringredistemplate stringredistemplate; @Test public void T1 () {valueoperations<string, string> stringstringvalueoperations = Stringredistemplat
E.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 jedisconn
Ectionfactory = (jedisconnectionfactory) stringredistemplate.getconnectionfactory ();
Jedisconnectionfactory.setdatabase (i);
Stringredistemplate.setconnectionfactory (jedisconnectionfactory);
Valueoperations valueoperations = Stringredistemplate.opsforvalue ();String test = (string) valueoperations.get ("test");
Logger.info (test); }
}
}
Run Testcredis.t2 (), the console prints "0, 1, 2", the database switch succeeded