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

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

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

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

說(shuō)明:

  • 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來(lái)序列化和反序列化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)行測(cè)試。

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

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

LettuceConnectionFactory

實(shí)例里邊有沒(méi)設(shè)置成功,如果沒(méi)有則調(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來(lái)序列化和反序列化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 
# 自動(dòng)刷新時(shí)間 
spring.redis.lettuce.cluster.refresh.period=60
# 開(kāi)啟自適應(yīng)刷新  
spring.redis.lettuce.cluster.refresh.adaptive=true  
spring.redis.timeout=60

2、Redis配置類RedisConfiguration,請(qǐng)務(wù)必開(kāi)啟集群自動(dòng)刷新拓?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);  
      // 配置集群自動(dòng)刷新拓?fù)?
     ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
         .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓?fù)? 
         .enableAllAdaptiveRefreshTriggers() //根據(jù)事件刷新拓?fù)? 
         .build();  
 
     ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()  
         //redis命令超時(shí)時(shí)間,超時(shí)后才會(huì)使用新的拓?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來(lái)序列化和反序列化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  
# 連接超時(shí)時(shí)間 
spring.redis.timeout=60s   
# 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制)  
spring.redis.lettuce.pool.max-active=50  
# 連接池中的最小空閑連接  
spring.redis.lettuce.pool.min-idle=5  
# 連接池中的最大空閑連接  
spring.redis.lettuce.pool.max-idle=50  
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制)  
spring.redis.lettuce.pool.max-wait=5000  
#eviction線程調(diào)度時(shí)間間隔  
spring.redis.lettuce.pool.time-between-eviction-runs=2000

2、redis配置類RedisConfiguration,請(qǐng)務(wù)必開(kāi)啟集群自動(dòng)刷新拓?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);  
      // 配置集群自動(dòng)刷新拓?fù)?
     ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
         .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓?fù)? 
         .enableAllAdaptiveRefreshTriggers() //根據(jù)事件刷新拓?fù)? 
         .build();  
 
     ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()  
         //redis命令超時(shí)時(shí)間,超時(shí)后才會(huì)使用新的拓?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來(lái)序列化和反序列化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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

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

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

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

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

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

    如何測(cè)試Java類的線程安全性

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

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

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

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

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

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

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

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

    這篇文章主要介紹了詳解SpringCloud Ribbon 負(fù)載均衡通過(guò)服務(wù)器名無(wú)法連接的神坑,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    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à)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • SpringMvc中容器加載的過(guò)程源碼詳解

    SpringMvc中容器加載的過(guò)程源碼詳解

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

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

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

最新評(píng)論

新化县| 类乌齐县| 赤水市| 罗山县| 额尔古纳市| 保康县| 儋州市| 巧家县| 富锦市| 昌都县| 克东县| 泰安市| 洛隆县| 南江县| 乌鲁木齐县| 连江县| 太白县| 石河子市| 高邮市| 昌邑市| 南乐县| 五指山市| 台州市| 德清县| 宿迁市| 吴忠市| 马龙县| 奉节县| 宜城市| 通渭县| 泗阳县| 达孜县| 建始县| 肥东县| 鄂托克前旗| 长海县| 衡阳县| 汉中市| 东光县| 平塘县| 图木舒克市|