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

關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例

 更新時間:2023年04月22日 09:09:55   作者:帥氣的梧桐述  
這篇文章主要介紹了關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

首先使用maven在pom.xml添加如下依賴

說明:

  • SpringBoot從2.0起默認(rèn)使用lettuce客戶端進(jìn)行連接。
  • 此次使用的版本: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連接實(shí)例

Springboot+Lettuce單連方式連接Redis單機(jī)/主備/Proxy集群示例。

1、在application.properties配置文件中加上redis相關(guān)配置。 

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替換默認(rèn)的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類進(jìn)行測試。

@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單機(jī)/主備/Proxy集群示例。

 1、在上邊maven依賴的基礎(chǔ)上添加以下依賴。

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

2、在application.properties配置文件中加上redis相關(guān)配置。

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

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

LettuceConnectionFactory

實(shí)例里邊有沒設(shè)置成功,如果沒有則調(diào)整成如下配置:

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替換默認(rèn)的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相關(guān)配置。

spring.redis.cluster.nodes=host:port  
spring.redis.cluster.max-redirects=3  
spring.redis.password= pwd 
# 自動刷新時間 
spring.redis.lettuce.cluster.refresh.period=60
# 開啟自適應(yīng)刷新  
spring.redis.lettuce.cluster.refresh.adaptive=true  
spring.redis.timeout=60

2、Redis配置類RedisConfiguration,請務(wù)必開啟集群自動刷新拓?fù)渑渲谩?/strong>

@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);  
      // 配置集群自動刷新拓?fù)?
     ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
         .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓?fù)? 
         .enableAllAdaptiveRefreshTriggers() //根據(jù)事件刷新拓?fù)? 
         .build();  
 
     ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()  
         //redis命令超時時間,超時后才會使用新的拓?fù)湫畔⒅匦陆⑦B接  
         .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period)))  
         .topologyRefreshOptions(topologyRefreshOptions)  
         .build();  
     LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()  
             .commandTimeout(Duration.ofSeconds(timeout))   
             .readFrom(ReadFrom.REPLICA_PREFERRED) // 優(yōu)先從副本讀取  
             .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替換默認(rèn)的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相關(guān)配置。

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   
# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制)  
spring.redis.lettuce.pool.max-active=50  
# 連接池中的最小空閑連接  
spring.redis.lettuce.pool.min-idle=5  
# 連接池中的最大空閑連接  
spring.redis.lettuce.pool.max-idle=50  
# 連接池最大阻塞等待時間(使用負(fù)值表示沒有限制)  
spring.redis.lettuce.pool.max-wait=5000  
#eviction線程調(diào)度時間間隔  
spring.redis.lettuce.pool.time-between-eviction-runs=2000

2、redis配置類RedisConfiguration,請務(wù)必開啟集群自動刷新拓?fù)渑渲谩?/strong>

@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);  
      // 配置集群自動刷新拓?fù)?
     ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
         .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓?fù)? 
         .enableAllAdaptiveRefreshTriggers() //根據(jù)事件刷新拓?fù)? 
         .build();  
 
     ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()  
         //redis命令超時時間,超時后才會使用新的拓?fù)湫畔⒅匦陆⑦B接  
         .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period)))  
         .topologyRefreshOptions(topologyRefreshOptions)  
         .build();  
     LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()  
             .commandTimeout(Duration.ofSeconds(timeout))  
             .poolConfig(genericObjectPoolConfig)  
             .readFrom(ReadFrom.REPLICA_PREFERRED) // 優(yōu)先從副本讀取  
             .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替換默認(rèn)的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;  
}  

推薦使用連接池方式。

到此這篇關(guān)于關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例的文章就介紹到這了,更多相關(guān)SpringBoot集成Lettuce連接Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot獲取Request請求的三種方式小結(jié)

    SpringBoot獲取Request請求的三種方式小結(jié)

    本文介紹了SpringBoot中獲取Request對象的三種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-12-12
  • Springboot中yml文件沒有葉子圖標(biāo)的解決

    Springboot中yml文件沒有葉子圖標(biāo)的解決

    這篇文章主要介紹了Springboot中yml文件沒有葉子圖標(biāo)的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 如何測試Java類的線程安全性

    如何測試Java類的線程安全性

    這篇文章主要介紹了如何測試Java類的線程安全性,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Java設(shè)計(jì)模式之抽象工廠模式淺析講解

    Java設(shè)計(jì)模式之抽象工廠模式淺析講解

    當(dāng)系統(tǒng)所提供的工廠所需生產(chǎn)的具體產(chǎn)品并不是一個簡單的對象,而是多個位于不同產(chǎn)品等級結(jié)構(gòu)中屬于不同類型的具體產(chǎn)品時需要使用抽象工廠模式,抽象工廠模式是所有形式的工廠模式中最為抽象和最具一般性的一種形態(tài)
    2022-08-08
  • IDEA解決springboot熱部署失效問題(推薦)

    IDEA解決springboot熱部署失效問題(推薦)

    熱部署,就是在應(yīng)用正在運(yùn)行的時候升級軟件,卻不需要重新啟動應(yīng)用。這篇文章主要介紹了IDEA解決springboot熱部署失效問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • Mybatis日志參數(shù)快速替換占位符工具的詳細(xì)步驟

    Mybatis日志參數(shù)快速替換占位符工具的詳細(xì)步驟

    這篇文章主要介紹了Mybatis日志參數(shù)快速替換占位符工具的詳細(xì)步驟,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • 詳解SpringCloud Ribbon 負(fù)載均衡通過服務(wù)器名無法連接的神坑

    詳解SpringCloud Ribbon 負(fù)載均衡通過服務(wù)器名無法連接的神坑

    這篇文章主要介紹了詳解SpringCloud Ribbon 負(fù)載均衡通過服務(wù)器名無法連接的神坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-06-06
  • JAVA SpringBoot jar程序 Systemctl生產(chǎn)環(huán)境部署方案

    JAVA SpringBoot jar程序 Systemctl生產(chǎn)環(huán)境部署方案

    這篇文章主要介紹了JAVA SpringBoot jar程序 Systemctl生產(chǎn)環(huán)境部署方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • SpringMvc中容器加載的過程源碼詳解

    SpringMvc中容器加載的過程源碼詳解

    這篇文章主要介紹了SpringMvc中容器加載的過程源碼詳解,springmvc是基于spring的一個web層框架,同樣也是web層框架的有struts,struts2等等,但是struts因?yàn)槁┒吹葐栴},被慢慢淘汰了,現(xiàn)在基本都在用springmvc,需要的朋友可以參考下
    2023-11-11
  • LeetCode?動態(tài)規(guī)劃之矩陣區(qū)域和詳情

    LeetCode?動態(tài)規(guī)劃之矩陣區(qū)域和詳情

    這篇文章主要介紹了LeetCode?動態(tài)規(guī)劃之矩陣區(qū)域和詳情,文章基于Java的相關(guān)資料展開對LeetCode?動態(tài)規(guī)劃的詳細(xì)介紹,需要的小伙伴可以參考一下
    2022-04-04

最新評論

辰溪县| 化德县| 界首市| 兴文县| 柞水县| 泸水县| 青铜峡市| 博客| 竹山县| 烟台市| 凤山市| 合川市| 吕梁市| 枣阳市| 莫力| 利辛县| 宝鸡市| 武城县| 凤庆县| 磐石市| 仙游县| 阳西县| 甘肃省| 洪江市| 永泰县| 宝丰县| 大悟县| 二连浩特市| 巴塘县| 盐亭县| 嘉黎县| 周口市| 华安县| 通山县| 金塔县| 贵港市| 长岛县| 海淀区| 桑日县| 大兴区| 饶平县|