通过RedisTemplate连接多个Redis过程解析
前言
在集群环境的情况下连接多个Redis数据库是很正常的情况,因为平时都是使用本地环境的单Redis情况比较多,在这里用代码总结一下连接多个数据库的情况(主要是不同ip,同一个ip的不通数据库修改不通地方即可),这里还是使用的springboot提供的spring-boot-starter-data-redis工具包,具体介绍如下:
1.引入redis相关的jar
org.springframework.boot spring-boot-starter-parent 1.5.6.RELEASE org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-configuration-processor true
2.在配置文件application.properties文件中设置redis相关配置,这里我使用了一个本地的redis数据库,一个远程的redis数据库,这里只假设了ip地址不同,其他的配置都相同:
#配置缓存redis spring.redis.database=8 #Redis服务器地址 spring.redis.host=127.0.0.1 #Redis服务器连接端口 spring.redis.port=6379 #Redis服务器连接密码(默认为空) spring.redis.password= #连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 #连接池中的最大空闲连接 spring.redis.pool.max-idle=8 #连接池中的最小空闲连接 spring.redis.pool.min-idle=0 #连接超时时间(毫秒) spring.redis.keytimeout=1000 spring.redis.timeout=0 #配置第二个redis数据库地址 spring.redis.host2=172.19.3.150
3.添加RedisTemplate的Bean:
importcom.fasterxml.jackson.annotation.JsonAutoDetect;
importcom.fasterxml.jackson.annotation.PropertyAccessor;
importcom.fasterxml.jackson.databind.ObjectMapper;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.boot.autoconfigure.EnableAutoConfiguration;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.data.redis.connection.RedisConnectionFactory;
importorg.springframework.data.redis.connection.jedis.JedisConnectionFactory;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.data.redis.core.StringRedisTemplate;
importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
importorg.springframework.data.redis.serializer.RedisSerializer;
importorg.springframework.data.redis.serializer.StringRedisSerializer;
importredis.clients.jedis.JedisPoolConfig;
/**
*@authorliaoyubo
*@version1.02017/8/1
*@description
*/
@Configuration
publicclassRedisConfig{
@Value("${spring.redis.host}")
privateStringhostName;
@Value("${spring.redis.port}")
privateintport;
@Value("${spring.redis.password}")
privateStringpassWord;
@Value("${spring.redis.pool.max-idle}")
privateintmaxIdl;
@Value("${spring.redis.pool.min-idle}")
privateintminIdl;
@Value("${spring.redis.database}")
privateintdatabase;
@Value("${spring.redis.keytimeout}")
privatelongkeytimeout;
@Value("${spring.redis.timeout}")
privateinttimeout;
@Value("${spring.redis.host2}")
privateStringhostName2;
/*@Bean
publicJedisConnectionFactoryredisConnectionFactory(){
JedisConnectionFactoryfactory=newJedisConnectionFactory();
factory.setHostName(hostName);
factory.setPort(port);
factory.setTimeout(timeout);//设置连接超时时间
returnfactory;
}
@Bean
publicRedisTemplateredisTemplate(RedisConnectionFactoryfactory){
StringRedisTemplatetemplate=newStringRedisTemplate(factory);
setSerializer(template);//设置序列化工具,这样ReportBean不需要实现Serializable接口
template.afterPropertiesSet();
returntemplate;
}
privatevoidsetSerializer(StringRedisTemplatetemplate){
Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class);
ObjectMapperom=newObjectMapper();
om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}*/
@Bean
publicRedisConnectionFactoryredisConnectionFactory(){
JedisPoolConfigpoolConfig=newJedisPoolConfig();
poolConfig.setMaxIdle(maxIdl);
poolConfig.setMinIdle(minIdl);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);
JedisConnectionFactoryjedisConnectionFactory=newJedisConnectionFactory(poolConfig);
jedisConnectionFactory.setHostName(hostName);
if(!passWord.isEmpty()){
jedisConnectionFactory.setPassword(passWord);
}
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setDatabase(database);
returnjedisConnectionFactory;
}
@Bean
publicRedisConnectionFactoryredisConnectionFactory2(){
JedisPoolConfigpoolConfig=newJedisPoolConfig();
poolConfig.setMaxIdle(maxIdl);
poolConfig.setMinIdle(minIdl);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);
JedisConnectionFactoryjedisConnectionFactory=newJedisConnectionFactory(poolConfig);
jedisConnectionFactory.setHostName(hostName2);
if(!passWord.isEmpty()){
jedisConnectionFactory.setPassword(passWord);
}
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setDatabase(database);
returnjedisConnectionFactory;
}
@Bean(name="redisTemplate1")
publicRedisTemplateredisTemplateObject()throwsException{
RedisTemplateredisTemplateObject=newRedisTemplate();
redisTemplateObject.setConnectionFactory(redisConnectionFactory());
setSerializer(redisTemplateObject);
redisTemplateObject.afterPropertiesSet();
returnredisTemplateObject;
}
@Bean(name="redisTemplate2")
publicRedisTemplateredisTemplateObject2()throwsException{
RedisTemplateredisTemplateObject=newRedisTemplate();
redisTemplateObject.setConnectionFactory(redisConnectionFactory2());
setSerializer(redisTemplateObject);
redisTemplateObject.afterPropertiesSet();
returnredisTemplateObject;
}
privatevoidsetSerializer(RedisTemplatetemplate){
Jackson2JsonRedisSerializer
4.App启动类:
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
/**
*@authorliaoyubo
*@version1.02017/7/31
*@description
*/
@SpringBootApplication
publicclassApp{
publicstaticvoidmain(String[]args){
SpringApplication.run(App.class);
}
}
5.测试多个Redis数据库连接:
importcom.springRedis.App;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.dao.DataAccessException;
importorg.springframework.data.redis.connection.RedisConnection;
importorg.springframework.data.redis.core.RedisCallback;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.test.context.junit4.SpringRunner;
importjavax.annotation.Resource;
/**
*@authorliaoyubo
*@version1.02017/7/31
*@description
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes=App.class)
publicclassPipelineTest{
@Autowired
@Resource(name="redisTemplate1")
privateRedisTemplateredisTemplate1;
@Autowired
@Resource(name="redisTemplate2")
privateRedisTemplateredisTemplate2;
@Test
publicvoidtestPipeLine(){
redisTemplate1.opsForValue().set("a",1);
redisTemplate1.opsForValue().set("b",2);
/*redisTemplate1.executePipelined(newRedisCallback(){
@Override
publicObjectdoInRedis(RedisConnectionredisConnection)throwsDataAccessException{
redisConnection.openPipeline();
for(inti=0;i<10;i++){
redisConnection.incr("a".getBytes());
}
System.out.println("a:"+redisTemplate1.opsForValue().get("a"));
redisTemplate1.opsForValue().set("c",3);
for(intj=0;j<20;j++){
redisConnection.incr("b".getBytes());
}
System.out.println("b:"+redisTemplate1.opsForValue().get("b"));
System.out.println("c:"+redisTemplate1.opsForValue().get("c"));
redisConnection.closePipeline();
returnnull;
}
});*/
System.out.println("b:"+redisTemplate1.opsForValue().get("b"));
System.out.println("a:"+redisTemplate1.opsForValue().get("a"));
redisTemplate2.opsForValue().set("m",5);
redisTemplate2.opsForValue().set("n",6);
System.out.println("m:"+redisTemplate2.opsForValue().get("m"));
System.out.println("n:"+redisTemplate2.opsForValue().get("n"));
}
以上就是连接2个Redis数据库的例子,在这里还有一个需要注意的是不能将
privateRedisTemplateredisTemplate1
代码中的redisTemplate1修改为redisTemplate,因为这个redisTemplate可能是程序中默认的全局变量,具体的代码逻辑没有去查看,如果修改为了redisTemplate的话会出现以下错误:
Causedby:org.springframework.beans.factory.NoUniqueBeanDefinitionException:Noqualifyingbeanoftype'org.springframework.data.redis.core.RedisTemplate,?>'available:expectedsinglematchingbeanbutfound2:redisTemplate1,redisTemplate2 atorg.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) atorg.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ...33more
如果在设置RedisConnectionFactory的连接工厂时,一定要保留一个如下的代码:
publicRedisConnectionFactoryredisConnectionFactory()
否则会出现以下错误:
Causedby:org.springframework.beans.factory.NoUniqueBeanDefinitionException:Noqualifyingbeanoftype'org.springframework.data.redis.connection.RedisConnectionFactory'available:expectedsinglematchingbeanbutfound2:redisConnectionFactory1,redisConnectionFactory2 atorg.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) atorg.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) atorg.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ...47more
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。