首頁 > 軟體

關於SpringBoot整合Lettuce連線Redis的方法和案例

2023-09-05 18:04:58

首先使用maven在pom.xml新增如下依賴

說明:

  • SpringBoot從2.0起預設使用lettuce使用者端進行連線。
  • 此次使用的版本:springboot:2.6.6,lettuce:6.1.8。
<dependency> 
  <groupId>org.springframework.boot</groupId>  
  <artifactId>spring-boot-starter-web</artifactId>  
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>  
  <artifactId>spring-boot-starter-data-redis</artifactId>  
</dependency>

 使用SpringBoot整合Lettuce連線範例

Springboot+Lettuce單連方式連線Redis單機/主備/Proxy叢集範例。

1、在application.properties組態檔中加上redis相關設定。 

spring.redis.host=host  
spring.redis.database=0  
spring.redis.password=pwd 
spring.redis.port=port

2、Redis設定類RedisConfiguration。

@Bean  
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {   
    RedisTemplate<String, Object> template = new RedisTemplate<>();  
    template.setConnectionFactory(lettuceConnectionFactory);  
    //使用Jackson2JsonRedisSerializer替換預設的JdkSerializationRedisSerializer來序列化和反序列化redis的value值  
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);  
    ObjectMapper mapper = new ObjectMapper();  
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
    mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,  
        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);  
    jackson2JsonRedisSerializer.setObjectMapper(mapper);  
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();  
    //key採用String的序列化方式  
    template.setKeySerializer(stringRedisSerializer);  
    // hash的key也採用String的序列化方式  
    template.setHashKeySerializer(stringRedisSerializer);  
    // value序列化方式採用jackson  
    template.setValueSerializer(jackson2JsonRedisSerializer);  
    // hash的value序列化方式採用jackson  
    template.setHashValueSerializer(jackson2JsonRedisSerializer);  
    template.afterPropertiesSet();  
    return template;  
}  

3、Redis操作類RedisUtil。

 /** 
  * 普通快取獲取 
  * @param key 鍵 
  * @return 值 
  */  
 public Object get(String key){  
     return key==null?null:redisTemplate.opsForValue().get(key);  
 }  
 
 /** 
  * 普通快取放入 
  * @param key 鍵 
  * @param value 值 
  * @return true成功 false失敗 
  */  
 public boolean set(String key,Object value) {  
     try {  
         redisTemplate.opsForValue().set(key, value);  
         return true;  
     } catch (Exception e) {  
         e.printStackTrace();  
         return false;  
     }  
 }

4、編寫controller類進行測試。

@RestController  
public class HelloRedis {  
    @Autowired  
    RedisUtil redisUtil;  
 
 
    @RequestMapping("/setParams")  
    @ResponseBody  
    public String setParams(String name) {  
	    redisUtil.set("name", name);  
	    return "success";  
	}  
	
    @RequestMapping("/getParams")  
    @ResponseBody  
    public String getParams(String name) {  
	   System.out.println("--------------" + name + "-------------");  
	   String retName = redisUtil.get(name) + "";  
	   return retName;  
	}  
	
}  

SpringBoot+Lettuce連線池方式連線Redis單機/主備/Proxy叢集範例。

 1、在上邊maven依賴的基礎上新增以下依賴。

<dependency>  
  <groupId>org.apache.commons</groupId>  
  <artifactId>commons-pool2</artifactId>  
</dependency> 

2、在application.properties組態檔中加上redis相關設定。

spring.redis.host=host  
spring.redis.database=0  
spring.redis.password=pwd  
spring.redis.port=port  
# 連線超時時間  
spring.redis.timeout=1000  
# 連線池最大連線數(使用負值表示沒有限制)  
spring.redis.lettuce.pool.max-active=50  
# 連線池中的最小空閒連線  
spring.redis.lettuce.pool.min-idle=5  
# 連線池中的最大空閒連線  
spring.redis.lettuce.pool.max-idle=50  
# 連線池最大阻塞等待時間(使用負值表示沒有限制)  
spring.redis.lettuce.pool.max-wait=5000  
#eviction執行緒排程時間間隔  
spring.redis.pool.time-between-eviction-runs-millis=2000  

 這裡最後的這個設定:spring.redis.pool.time-between-eviction-runs-millis=2000 在某些版本中會不生效,需要自己DEBUG看一下

LettuceConnectionFactory

範例裡邊有沒設定成功,如果沒有則調整成如下設定:

spring.redis.lettuce.pool.time-between-eviction-runs=2000

3、Redis連線設定類RedisConfiguration。

@Bean  
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {  
    lettuceConnectionFactory.setShareNativeConnection(false);  
    RedisTemplate<String, Object> template = new RedisTemplate<>();  
    template.setConnectionFactory(lettuceConnectionFactory);  
    //使用Jackson2JsonRedisSerializer替換預設的JdkSerializationRedisSerializer來序列化和反序列化redis的value值  
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);  
    ObjectMapper mapper = new ObjectMapper();  
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
    mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,  
        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);  
    jackson2JsonRedisSerializer.setObjectMapper(mapper);  
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();  
    //key採用String的序列化方式  
    template.setKeySerializer(stringRedisSerializer);  
    // hash的key也採用String的序列化方式  
    template.setHashKeySerializer(stringRedisSerializer);  
    // value序列化方式採用jackson  
    template.setValueSerializer(jackson2JsonRedisSerializer);  
    // hash的value序列化方式採用jackson  
    template.setHashValueSerializer(jackson2JsonRedisSerializer);  
    template.afterPropertiesSet();  
    return template;  
}  

SpringBoot+Lettuce單連線方式連線Redis Cluster叢集程式碼範例。

1、在application.properties組態檔中加上redis相關設定。

spring.redis.cluster.nodes=host:port  
spring.redis.cluster.max-redirects=3  
spring.redis.password= pwd 
# 自動重新整理時間 
spring.redis.lettuce.cluster.refresh.period=60
# 開啟自適應重新整理  
spring.redis.lettuce.cluster.refresh.adaptive=true  
spring.redis.timeout=60

2、Redis設定類RedisConfiguration,請務必開啟叢集自動重新整理拓撲設定。

@Bean  
public LettuceConnectionFactory lettuceConnectionFactory() {  
     String[] nodes = clusterNodes.split(",");  
     List<RedisNode> listNodes = new ArrayList();  
     for (String node : nodes) {  
         String[] ipAndPort = node.split(":");  
         RedisNode redisNode = new RedisNode(ipAndPort[0], Integer.parseInt(ipAndPort[1]));  
         listNodes.add(redisNode);  
     }  
     RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();  
     redisClusterConfiguration.setClusterNodes(listNodes);  
     redisClusterConfiguration.setPassword(password);  
     redisClusterConfiguration.setMaxRedirects(maxRedirects);  
      // 設定叢集自動重新整理拓撲 
     ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
         .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照週期重新整理拓撲  
         .enableAllAdaptiveRefreshTriggers() //根據事件重新整理拓撲  
         .build();  
 
     ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()  
         //redis命令超時時間,超時後才會使用新的拓撲資訊重新建立連線  
         .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period)))  
         .topologyRefreshOptions(topologyRefreshOptions)  
         .build();  
     LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()  
             .commandTimeout(Duration.ofSeconds(timeout))   
             .readFrom(ReadFrom.REPLICA_PREFERRED) // 優先從副本讀取  
             .clientOptions(clusterClientOptions)  
             .build();  
     LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);  
     return factory;  
}  
 
@Bean  
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {  
    RedisTemplate<String, Object> template = new RedisTemplate<>();  
    template.setConnectionFactory(lettuceConnectionFactory);  
    //使用Jackson2JsonRedisSerializer替換預設的JdkSerializationRedisSerializer來序列化和反序列化redis的value值  
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);  
    ObjectMapper mapper = new ObjectMapper();  
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
    mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,  
        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);  
    jackson2JsonRedisSerializer.setObjectMapper(mapper);  
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();  
    //key採用String的序列化方式  
    template.setKeySerializer(stringRedisSerializer);  
    // hash的key也採用String的序列化方式  
    template.setHashKeySerializer(stringRedisSerializer);  
    // value序列化方式採用jackson  
    template.setValueSerializer(jackson2JsonRedisSerializer);  
    // hash的value序列化方式採用jackson  
    template.setHashValueSerializer(jackson2JsonRedisSerializer);  
    template.afterPropertiesSet();  
    return template;  
}  

springboot+lettuce連線池方式連線Redis Cluster叢集程式碼範例。

1、在application.properties組態檔中加上Redis相關設定。

spring.redis.cluster.nodes=host:port  
spring.redis.cluster.max-redirects=3  
spring.redis.password=pwd 
spring.redis.lettuce.cluster.refresh.period=60  
spring.redis.lettuce.cluster.refresh.adaptive=true  
# 連線超時時間 
spring.redis.timeout=60s   
# 連線池最大連線數(使用負值表示沒有限制)  
spring.redis.lettuce.pool.max-active=50  
# 連線池中的最小空閒連線  
spring.redis.lettuce.pool.min-idle=5  
# 連線池中的最大空閒連線  
spring.redis.lettuce.pool.max-idle=50  
# 連線池最大阻塞等待時間(使用負值表示沒有限制)  
spring.redis.lettuce.pool.max-wait=5000  
#eviction執行緒排程時間間隔  
spring.redis.lettuce.pool.time-between-eviction-runs=2000

2、redis設定類RedisConfiguration,請務必開啟叢集自動重新整理拓撲設定。

@Bean  
 public LettuceConnectionFactory lettuceConnectionFactory() {  
     GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();  
     genericObjectPoolConfig.setMaxIdle(maxIdle);  
     genericObjectPoolConfig.setMinIdle(minIdle);  
     genericObjectPoolConfig.setMaxTotal(maxActive);  
     genericObjectPoolConfig.setMaxWait(Duration.ofMillis(maxWait));  
     genericObjectPoolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(timeBetweenEvictionRunsMillis));  
     String[] nodes = clusterNodes.split(",");  
     List<RedisNode> listNodes = new ArrayList();  
     for (String node : nodes) {  
         String[] ipAndPort = node.split(":");  
         RedisNode redisNode = new RedisNode(ipAndPort[0], Integer.parseInt(ipAndPort[1]));  
         listNodes.add(redisNode);  
     }  
     RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();  
     redisClusterConfiguration.setClusterNodes(listNodes);  
     redisClusterConfiguration.setPassword(password);  
     redisClusterConfiguration.setMaxRedirects(maxRedirects);  
      // 設定叢集自動重新整理拓撲 
     ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
         .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照週期重新整理拓撲  
         .enableAllAdaptiveRefreshTriggers() //根據事件重新整理拓撲  
         .build();  
 
     ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()  
         //redis命令超時時間,超時後才會使用新的拓撲資訊重新建立連線  
         .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period)))  
         .topologyRefreshOptions(topologyRefreshOptions)  
         .build();  
     LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()  
             .commandTimeout(Duration.ofSeconds(timeout))  
             .poolConfig(genericObjectPoolConfig)  
             .readFrom(ReadFrom.REPLICA_PREFERRED) // 優先從副本讀取  
             .clientOptions(clusterClientOptions)  
             .build();  
     LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);  
     return factory;  
 }  
 
@Bean  
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {  
    lettuceConnectionFactory.setShareNativeConnection(false);  
    RedisTemplate<String, Object> template = new RedisTemplate<>();  
    template.setConnectionFactory(lettuceConnectionFactory);  
    //使用Jackson2JsonRedisSerializer替換預設的JdkSerializationRedisSerializer來序列化和反序列化redis的value值  
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);  
    ObjectMapper mapper = new ObjectMapper();  
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
    mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,  
        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);  
    jackson2JsonRedisSerializer.setObjectMapper(mapper);  
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();  
    //key採用String的序列化方式  
    template.setKeySerializer(stringRedisSerializer);  
    // hash的key也採用String的序列化方式  
    template.setHashKeySerializer(stringRedisSerializer);  
    // value序列化方式採用jackson  
    template.setValueSerializer(jackson2JsonRedisSerializer);  
    // hash的value序列化方式採用jackson  
    template.setHashValueSerializer(jackson2JsonRedisSerializer);  
    template.afterPropertiesSet();  
    return template;  
}  

推薦使用連線池方式。

到此這篇關於關於SpringBoot整合Lettuce連線Redis的方法和案例的文章就介紹到這了,更多相關SpringBoot整合Lettuce連線Redis內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com