關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例
首先使用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對(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)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
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ì)步驟,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
詳解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)境部署方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03
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

