最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

通過RedisTemplate連接多個Redis過程解析

 更新時間:2019年08月22日 10:19:56   作者:357029540  
這篇文章主要介紹了通過RedisTemplate連接多個Redis過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

 前言

在集群環(huán)境的情況下連接多個Redis數(shù)據(jù)庫是很正常的情況,因為平時都是使用本地環(huán)境的單Redis情況比較多,在這里用代碼總結(jié)一下連接多個數(shù)據(jù)庫的情況(主要是不同ip,同一個ip的不通數(shù)據(jù)庫修改不通地方即可),這里還是使用的springboot提供的spring-boot-starter-data-redis工具包,具體介紹如下:

1.引入redis相關(guān)的jar

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.5.6.RELEASE</version> 
  </parent>  
  <dependencies> 
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-redis</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-test</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
    </dependency>   
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-configuration-processor</artifactId> 
      <optional>true</optional> 
    </dependency> 
  </dependencies> 

2.在配置文件application.properties文件中設(shè)置redis相關(guān)配置,這里我使用了一個本地的redis數(shù)據(jù)庫,一個遠程的redis數(shù)據(jù)庫,這里只假設(shè)了ip地址不同,其他的配置都相同:

#配置緩存redis 
spring.redis.database=8 
# Redis服務(wù)器地址 
spring.redis.host=127.0.0.1 
# Redis服務(wù)器連接端口 
spring.redis.port=6379 
# Redis服務(wù)器連接密碼(默認為空) 
spring.redis.password= 
# 連接池最大連接數(shù)(使用負值表示沒有限制) 
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數(shù)據(jù)庫地址 
spring.redis.host2=172.19.3.150 

3.添加RedisTemplate的Bean:

import com.fasterxml.jackson.annotation.JsonAutoDetect; 
import com.fasterxml.jackson.annotation.PropertyAccessor; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.data.redis.connection.RedisConnectionFactory; 
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.data.redis.core.StringRedisTemplate; 
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 
import org.springframework.data.redis.serializer.RedisSerializer; 
import org.springframework.data.redis.serializer.StringRedisSerializer; 
import redis.clients.jedis.JedisPoolConfig;  
/** 
 * @author liaoyubo 
 * @version 1.0 2017/8/1 
 * @description 
 */ 
@Configuration 
public class RedisConfig {  
  @Value("${spring.redis.host}") 
  private String hostName; 
  @Value("${spring.redis.port}") 
  private int port; 
  @Value("${spring.redis.password}") 
  private String passWord; 
  @Value("${spring.redis.pool.max-idle}") 
  private int maxIdl; 
  @Value("${spring.redis.pool.min-idle}") 
  private int minIdl; 
  @Value("${spring.redis.database}") 
  private int database; 
  @Value("${spring.redis.keytimeout}") 
  private long keytimeout; 
  @Value("${spring.redis.timeout}") 
  private int timeout; 
  @Value("${spring.redis.host2}") 
  private String hostName2; 
 
  /*@Bean 
  public JedisConnectionFactory redisConnectionFactory() { 
    JedisConnectionFactory factory = new JedisConnectionFactory(); 
    factory.setHostName(hostName); 
    factory.setPort(port); 
    factory.setTimeout(timeout); //設(shè)置連接超時時間 
    return factory; 
  } 
 
  @Bean 
  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { 
    StringRedisTemplate template = new StringRedisTemplate(factory); 
    setSerializer(template); //設(shè)置序列化工具,這樣ReportBean不需要實現(xiàn)Serializable接口 
    template.afterPropertiesSet(); 
    return template; 
  } 
  private void setSerializer(StringRedisTemplate template) { 
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 
    ObjectMapper om = new ObjectMapper(); 
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
    jackson2JsonRedisSerializer.setObjectMapper(om); 
    template.setValueSerializer(jackson2JsonRedisSerializer); 
  }*/ 
 
  @Bean 
  public RedisConnectionFactory redisConnectionFactory(){ 
    JedisPoolConfig poolConfig=new JedisPoolConfig(); 
    poolConfig.setMaxIdle(maxIdl); 
    poolConfig.setMinIdle(minIdl); 
    poolConfig.setTestOnBorrow(true); 
    poolConfig.setTestOnReturn(true); 
    poolConfig.setTestWhileIdle(true); 
    poolConfig.setNumTestsPerEvictionRun(10); 
    poolConfig.setTimeBetweenEvictionRunsMillis(60000); 
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig); 
    jedisConnectionFactory.setHostName(hostName); 
    if(!passWord.isEmpty()){ 
      jedisConnectionFactory.setPassword(passWord); 
    } 
    jedisConnectionFactory.setPort(port); 
    jedisConnectionFactory.setDatabase(database); 
    return jedisConnectionFactory; 
  }  
  @Bean 
  public RedisConnectionFactory redisConnectionFactory2(){ 
    JedisPoolConfig poolConfig=new JedisPoolConfig(); 
    poolConfig.setMaxIdle(maxIdl); 
    poolConfig.setMinIdle(minIdl); 
    poolConfig.setTestOnBorrow(true); 
    poolConfig.setTestOnReturn(true); 
    poolConfig.setTestWhileIdle(true); 
    poolConfig.setNumTestsPerEvictionRun(10); 
    poolConfig.setTimeBetweenEvictionRunsMillis(60000); 
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig); 
    jedisConnectionFactory.setHostName(hostName2); 
    if(!passWord.isEmpty()){ 
      jedisConnectionFactory.setPassword(passWord); 
    } 
    jedisConnectionFactory.setPort(port); 
    jedisConnectionFactory.setDatabase(database); 
    return jedisConnectionFactory; 
  }  
  @Bean(name = "redisTemplate1") 
  public RedisTemplate<String, Object> redisTemplateObject() throws Exception { 
    RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>(); 
    redisTemplateObject.setConnectionFactory(redisConnectionFactory()); 
    setSerializer(redisTemplateObject); 
    redisTemplateObject.afterPropertiesSet(); 
    return redisTemplateObject; 
  }  
  @Bean(name = "redisTemplate2") 
  public RedisTemplate<String, Object> redisTemplateObject2() throws Exception { 
    RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>(); 
    redisTemplateObject.setConnectionFactory(redisConnectionFactory2()); 
    setSerializer(redisTemplateObject); 
    redisTemplateObject.afterPropertiesSet(); 
    return redisTemplateObject; 
  }  
  private void setSerializer(RedisTemplate<String, Object> template) { 
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>( 
        Object.class); 
    ObjectMapper om = new ObjectMapper(); 
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
    jackson2JsonRedisSerializer.setObjectMapper(om); 
    template.setKeySerializer(template.getStringSerializer()); 
    template.setValueSerializer(jackson2JsonRedisSerializer); 
    template.setHashValueSerializer(jackson2JsonRedisSerializer); 
    //在使用String的數(shù)據(jù)結(jié)構(gòu)的時候使用這個來更改序列化方式 
    /*RedisSerializer<String> stringSerializer = new StringRedisSerializer(); 
    template.setKeySerializer(stringSerializer ); 
    template.setValueSerializer(stringSerializer ); 
    template.setHashKeySerializer(stringSerializer ); 
    template.setHashValueSerializer(stringSerializer );*/  
  }  
} 

4.App啟動類:

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication;  
/** 
 * @author liaoyubo 
 * @version 1.0 2017/7/31 
 * @description 
 */ 
@SpringBootApplication 
public class App {  
  public static void main(String [] args){ 
    SpringApplication.run(App.class); 
  }  
} 

5.測試多個Redis數(shù)據(jù)庫連接:

import com.springRedis.App; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.test.context.SpringBootTest; 
import org.springframework.dao.DataAccessException; 
import org.springframework.data.redis.connection.RedisConnection; 
import org.springframework.data.redis.core.RedisCallback; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.test.context.junit4.SpringRunner; 
import javax.annotation.Resource;  
/** 
 * @author liaoyubo 
 * @version 1.0 2017/7/31 
 * @description 
 */  
@RunWith(SpringRunner.class) 
@SpringBootTest(classes = App.class) 
public class PipelineTest {  
  @Autowired 
  @Resource(name = "redisTemplate1") 
  private RedisTemplate<String,Object> redisTemplate1;  
  @Autowired 
  @Resource(name = "redisTemplate2") 
  private RedisTemplate<String,Object> redisTemplate2;  
  @Test 
  public void testPipeLine(){ 
    redisTemplate1.opsForValue().set("a",1); 
    redisTemplate1.opsForValue().set("b",2); 
    /*redisTemplate1.executePipelined(new RedisCallback<Object>() { 
      @Override 
      public Object doInRedis(RedisConnection redisConnection) throws DataAccessException { 
        redisConnection.openPipeline(); 
        for (int i = 0;i < 10;i++){ 
          redisConnection.incr("a".getBytes()); 
        } 
        System.out.println("a:"+redisTemplate1.opsForValue().get("a")); 
        redisTemplate1.opsForValue().set("c",3); 
        for(int j = 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(); 
        return null; 
      } 
    });*/ 
    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數(shù)據(jù)庫的例子,在這里還有一個需要注意的是不能將

private RedisTemplate<String,Object> redisTemplate1 

代碼中的redisTemplate1修改為redisTemplate,因為這個redisTemplate可能是程序中默認的全局變量,具體的代碼邏輯沒有去查看,如果修改為了redisTemplate的話會出現(xiàn)以下錯誤:

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 
  at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173) 
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) 
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) 
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) 
  ... 33 more 

如果在設(shè)置RedisConnectionFactory的連接工廠時,一定要保留一個如下的代碼:

public RedisConnectionFactory redisConnectionFactory() 

否則會出現(xiàn)以下錯誤:

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 
  at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173) 
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) 
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) 
  at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) 
  at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) 
  ... 47 more 

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java單元測試Powermockito和Mockito使用總結(jié)

    Java單元測試Powermockito和Mockito使用總結(jié)

    公司單元測試框架選用了Junit 4.12,Mock框架選用了Mockito和PowerMock,本文主要介紹了Java單元測試Powermockito和Mockito使用總結(jié),感興趣的可以了解一下
    2021-09-09
  • 關(guān)于Springboot2.x集成lettuce連接redis集群報超時異常Command timed out after 6 second(s)

    關(guān)于Springboot2.x集成lettuce連接redis集群報超時異常Command timed out afte

    這篇文章主要介紹了Springboot2.x集成lettuce連接redis集群報超時異常Command timed out after 6 second(s),本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2021-03-03
  • springboot熱部署class XX cannot be cast to class XX解決方案

    springboot熱部署class XX cannot be cast&nbs

    在使用DevTools進行熱加載時遇到的`classXXcannotbecasttoclassXX`錯誤,以及解決該問題的方法,通過在`resources`目錄下創(chuàng)建`META-INF/spring-devtools.properties`文件,并添加相應(yīng)的配置,可以有效解決此問題,使DevTools熱加載功能得以正常工作
    2025-02-02
  • Spring Security表單配置過程分步講解

    Spring Security表單配置過程分步講解

    SpringSecurity的配置基于WebSecurityConfigurerAdapter的實現(xiàn)類,我們這里主要講基本配置,即configure(HttpSecurity http)方法的配置,其實大都有默認值,我們可以直接用默認值,也可以自己設(shè)置
    2023-01-01
  • 詳解Java中Quartz的簡單使用

    詳解Java中Quartz的簡單使用

    Quartz?是一個開源的作業(yè)調(diào)度框架,它完全由?Java?寫成,并設(shè)計用于?J2SE?和?J2EE?應(yīng)用中。這篇文章主要通過示例和大家講講Quartz的簡單使用,需要的可以參考一下
    2023-04-04
  • Java中進程與線程的區(qū)別

    Java中進程與線程的區(qū)別

    這篇文章主要介紹了Java進程與線程的區(qū)別,進程(Process)是操作系統(tǒng)分配資源的基本單位,線程(Thread)是操作系統(tǒng)能夠進行運算調(diào)度的基本單位,下文更多兩者區(qū)別。需要的小伙伴可以參考一下
    2022-05-05
  • java實現(xiàn)去除ArrayList重復(fù)字符串

    java實現(xiàn)去除ArrayList重復(fù)字符串

    本文主要介紹了java實現(xiàn)去除ArrayList重復(fù)字符串,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-09-09
  • 詳解java中命令行模式的實現(xiàn)

    詳解java中命令行模式的實現(xiàn)

    命令模式是一種行為設(shè)計模式,它允許您將請求封裝為對象,以便您可以將其參數(shù)化、隊列化、記錄和撤銷,本文主要為大家介紹一下java實現(xiàn)命令模式的示例代碼,需要的可以參考下
    2023-09-09
  • mybatis配置文件簡介_動力節(jié)點Java學(xué)院整理

    mybatis配置文件簡介_動力節(jié)點Java學(xué)院整理

    這篇文章主要為大家詳細介紹了mybatis配置文件簡介的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • SpringBoot利用自定義注解實現(xiàn)多數(shù)據(jù)源

    SpringBoot利用自定義注解實現(xiàn)多數(shù)據(jù)源

    這篇文章主要為大家詳細介紹了SpringBoot如何利用自定義注解實現(xiàn)多數(shù)據(jù)源效果,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以了解一下
    2022-10-10

最新評論

大邑县| 连南| 孙吴县| 新巴尔虎左旗| 阜新| 温州市| 太湖县| 兴仁县| 汉中市| 布尔津县| 永清县| 皋兰县| 象山县| 玛纳斯县| 得荣县| 天等县| 永兴县| 闻喜县| 剑河县| 铁岭市| 松桃| 昌平区| 许昌县| 宜阳县| 沛县| 务川| 南汇区| 宜兰市| 鄂伦春自治旗| 大安市| 嘉鱼县| 桃园市| 阿拉善左旗| 沁源县| 洛川县| 新巴尔虎右旗| 稻城县| 沛县| 招远市| 宁陕县| 灵璧县|