通过RedisTemplate连接多个Redis

4 篇文章 0 订阅
2 篇文章 0 订阅

     在集群环境的情况下连接多个Redis数据库是很正常的情况,因为平时都是使用本地环境的单Redis情况比较多,在这里用代码总结一下连接多个数据库的情况(主要是不同ip,同一个ip的不通数据库修改不通地方即可),这里还是使用的springboot提供的spring-boot-starter-data-redis工具包,具体介绍如下:

      1.引入redis相关的jar

       

Xml代码  

  1. <parent>  
  2.         <groupId>org.springframework.boot</groupId>  
  3.         <artifactId>spring-boot-starter-parent</artifactId>  
  4.         <version>1.5.6.RELEASE</version>  
  5.     </parent>  
  6.     <dependencies>  
  7.         <dependency>  
  8.             <groupId>org.springframework.boot</groupId>  
  9.             <artifactId>spring-boot-starter-data-redis</artifactId>  
  10.         </dependency>  
  11.         <dependency>  
  12.             <groupId>org.springframework.boot</groupId>  
  13.             <artifactId>spring-boot-starter-test</artifactId>  
  14.         </dependency>  
  15.         <dependency>  
  16.             <groupId>org.springframework.boot</groupId>  
  17.             <artifactId>spring-boot-starter-web</artifactId>  
  18.         </dependency>  
  19.         <dependency>  
  20.             <groupId>org.springframework.boot</groupId>  
  21.             <artifactId>spring-boot-configuration-processor</artifactId>  
  22.             <optional>true</optional>  
  23.         </dependency>  
  24.     </dependencies>  

         2.在配置文件application.properties文件中设置redis相关配置,这里我使用了一个本地的redis数据库,一个远程的redis数据库,这里只假设了ip地址不同,其他的配置都相同:

Java代码  

  1. #配置缓存redis  
  2. spring.redis.database=8  
  3. # Redis服务器地址  
  4. spring.redis.host=127.0.0.1  
  5. # Redis服务器连接端口  
  6. spring.redis.port=6379  
  7. # Redis服务器连接密码(默认为空)  
  8. spring.redis.password=  
  9. # 连接池最大连接数(使用负值表示没有限制)  
  10. spring.redis.pool.max-active=8  
  11. # 连接池最大阻塞等待时间(使用负值表示没有限制)  
  12. spring.redis.pool.max-wait=-1  
  13. # 连接池中的最大空闲连接  
  14. spring.redis.pool.max-idle=8  
  15. # 连接池中的最小空闲连接  
  16. spring.redis.pool.min-idle=0  
  17. # 连接超时时间(毫秒)  
  18. spring.redis.keytimeout=1000  
  19. spring.redis.timeout=0  
  20.   
  21. #配置第二个redis数据库地址  
  22. spring.redis.host2=172.19.3.150  

     3.添加RedisTemplate的Bean:

Java代码  

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;  
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;  
  3. import com.fasterxml.jackson.databind.ObjectMapper;  
  4. import org.springframework.beans.factory.annotation.Value;  
  5. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
  6. import org.springframework.context.annotation.Bean;  
  7. import org.springframework.context.annotation.Configuration;  
  8. import org.springframework.data.redis.connection.RedisConnectionFactory;  
  9. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
  10. import org.springframework.data.redis.core.RedisTemplate;  
  11. import org.springframework.data.redis.core.StringRedisTemplate;  
  12. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;  
  13. import org.springframework.data.redis.serializer.RedisSerializer;  
  14. import org.springframework.data.redis.serializer.StringRedisSerializer;  
  15. import redis.clients.jedis.JedisPoolConfig;  
  16.   
  17. /** 
  18.  * @author liaoyubo 
  19.  * @version 1.0 2017/8/1 
  20.  * @description 
  21.  */  
  22. @Configuration  
  23. public class RedisConfig {  
  24.     @Value("${spring.redis.host}")  
  25.     private String hostName;  
  26.     @Value("${spring.redis.port}")  
  27.     private int port;  
  28.     @Value("${spring.redis.password}")  
  29.     private String passWord;  
  30.     @Value("${spring.redis.pool.max-idle}")  
  31.     private int maxIdl;  
  32.     @Value("${spring.redis.pool.min-idle}")  
  33.     private int minIdl;  
  34.     @Value("${spring.redis.database}")  
  35.     private int database;  
  36.     @Value("${spring.redis.keytimeout}")  
  37.     private long keytimeout;  
  38.     @Value("${spring.redis.timeout}")  
  39.     private int timeout;  
  40.     @Value("${spring.redis.host2}")  
  41.     private String hostName2;    
  42.     @Bean  
  43.     public RedisConnectionFactory redisConnectionFactory(){  
  44.         JedisPoolConfig poolConfig=new JedisPoolConfig();  
  45.         poolConfig.setMaxIdle(maxIdl);  
  46.         poolConfig.setMinIdle(minIdl);  
  47.         poolConfig.setTestOnBorrow(true);  
  48.         poolConfig.setTestOnReturn(true);  
  49.         poolConfig.setTestWhileIdle(true);  
  50.         poolConfig.setNumTestsPerEvictionRun(10);  
  51.         poolConfig.setTimeBetweenEvictionRunsMillis(60000);  
  52.         JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);  
  53.         jedisConnectionFactory.setHostName(hostName);  
  54.         if(!passWord.isEmpty()){  
  55.             jedisConnectionFactory.setPassword(passWord);  
  56.         }  
  57.         jedisConnectionFactory.setPort(port);  
  58.         jedisConnectionFactory.setDatabase(database);  
  59.         return jedisConnectionFactory;  
  60.     }  
  61.     @Bean  
  62.     public RedisConnectionFactory redisConnectionFactory2(){  
  63.         JedisPoolConfig poolConfig=new JedisPoolConfig();  
  64.         poolConfig.setMaxIdle(maxIdl);  
  65.         poolConfig.setMinIdle(minIdl);  
  66.         poolConfig.setTestOnBorrow(true);  
  67.         poolConfig.setTestOnReturn(true);  
  68.         poolConfig.setTestWhileIdle(true);  
  69.         poolConfig.setNumTestsPerEvictionRun(10);  
  70.         poolConfig.setTimeBetweenEvictionRunsMillis(60000);  
  71.         JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);  
  72.         jedisConnectionFactory.setHostName(hostName2);  
  73.         if(!passWord.isEmpty()){  
  74.             jedisConnectionFactory.setPassword(passWord);  
  75.         }  
  76.         jedisConnectionFactory.setPort(port);  
  77.         jedisConnectionFactory.setDatabase(database);  
  78.         return jedisConnectionFactory;  
  79.     }  
  80.     @Bean(name = "redisTemplate1")  
  81.     public RedisTemplate<String, Object> redisTemplateObject() throws Exception {  
  82.         RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>();  
  83.         redisTemplateObject.setConnectionFactory(redisConnectionFactory());  
  84.         setSerializer(redisTemplateObject);  
  85.         redisTemplateObject.afterPropertiesSet();  
  86.         return redisTemplateObject;  
  87.     }  
  88.     @Bean(name = "redisTemplate2")  
  89.     public RedisTemplate<String, Object> redisTemplateObject2() throws Exception {  
  90.         RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>();  
  91.         redisTemplateObject.setConnectionFactory(redisConnectionFactory2());  
  92.         setSerializer(redisTemplateObject);  
  93.         redisTemplateObject.afterPropertiesSet();  
  94.         return redisTemplateObject;  
  95.     }  
  96.     private void setSerializer(RedisTemplate<String, Object> template) {  
  97.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(  
  98.                 Object.class);  
  99.         ObjectMapper om = new ObjectMapper();  
  100.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
  101.         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
  102.         jackson2JsonRedisSerializer.setObjectMapper(om);  
  103.         template.setKeySerializer(template.getStringSerializer());  
  104.         template.setValueSerializer(jackson2JsonRedisSerializer);  
  105.         template.setHashValueSerializer(jackson2JsonRedisSerializer);  
  106.         //在使用String的数据结构的时候使用这个来更改序列化方式  
  107.         /*RedisSerializer<String> stringSerializer = new StringRedisSerializer(); 
  108.         template.setKeySerializer(stringSerializer ); 
  109.         template.setValueSerializer(stringSerializer ); 
  110.         template.setHashKeySerializer(stringSerializer ); 
  111.         template.setHashValueSerializer(stringSerializer );*/  
  112.     }  
  113. }  

      4.App启动类:

Java代码  

  1. import org.springframework.boot.SpringApplication;  
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  3.   
  4. /** 
  5.  * @author liaoyubo 
  6.  * @version 1.0 2017/7/31 
  7.  * @description 
  8.  */  
  9. @SpringBootApplication  
  10. public class App {  
  11.   
  12.     public static void main(String [] args){  
  13.         SpringApplication.run(App.class);  
  14.     }  
  15.   
  16. }  

     5.测试多个Redis数据库连接:

Java代码  

  1. import com.springRedis.App;  
  2. import org.junit.Test;  
  3. import org.junit.runner.RunWith;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.boot.test.context.SpringBootTest;  
  6. import org.springframework.dao.DataAccessException;  
  7. import org.springframework.data.redis.connection.RedisConnection;  
  8. import org.springframework.data.redis.core.RedisCallback;  
  9. import org.springframework.data.redis.core.RedisTemplate;  
  10. import org.springframework.test.context.junit4.SpringRunner;  
  11.   
  12. import javax.annotation.Resource;  
  13.   
  14.   
  15. /** 
  16.  * @author liaoyubo 
  17.  * @version 1.0 2017/7/31 
  18.  * @description 
  19.  */  
  20.   
  21. @RunWith(SpringRunner.class)  
  22. @SpringBootTest(classes = App.class)  
  23. public class PipelineTest {  
  24.   
  25.     @Autowired  
  26.     @Resource(name = "redisTemplate1")  
  27.     private RedisTemplate<String,Object> redisTemplate1;  
  28.   
  29.     @Autowired  
  30.     @Resource(name = "redisTemplate2")  
  31.     private RedisTemplate<String,Object> redisTemplate2;  
  32.   
  33.     @Test  
  34.     public void testPipeLine(){  
  35.         redisTemplate1.opsForValue().set("a",1);  
  36.         redisTemplate1.opsForValue().set("b",2);  
  37.         System.out.println("b:"+redisTemplate1.opsForValue().get("b"));  
  38.         System.out.println("a:"+redisTemplate1.opsForValue().get("a"));  
  39.   
  40.         redisTemplate2.opsForValue().set("m",5);  
  41.         redisTemplate2.opsForValue().set("n",6);  
  42.         System.out.println("m:"+redisTemplate2.opsForValue().get("m"));  
  43.         System.out.println("n:"+redisTemplate2.opsForValue().get("n"));  
  44.     }  

以上就是连接2个Redis数据库的例子,在这里还有一个需要注意的是不能将

  1. private RedisTemplate<String,Object> redisTemplate1  

          代码中的redisTemplate1修改为redisTemplate,因为这个redisTemplate可能是程序中默认的全局变量,具体的代码逻辑没有去查看,如果修改为了redisTemplate的话会出现以下错误:

Java代码  

  1. Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<?, ?>' available: expected single matching bean but found 2: redisTemplate1,redisTemplate2  
  2.     at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)  
  3.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)  
  4.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)  
  5.     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)  
  6.     ... 33 more  

         如果在设置RedisConnectionFactory的连接工厂时,一定要保留一个如下的代码:

Java代码  

  1. public RedisConnectionFactory redisConnectionFactory()  

         否则会出现以下错误:

Java代码  

  1. Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory' available: expected single matching bean but found 2: redisConnectionFactory1,redisConnectionFactory2  
  2.     at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)  
  3.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)  
  4.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)  
  5.     at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)  
  6.     at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)  
  7.     ... 47 more  

原文地址:http://357029540.iteye.com/blog/2389235

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值