博客
关于我
SpringBoot集成Lettuce
阅读量:797 次
发布时间:2023-03-22

本文共 7970 字,大约阅读时间需要 26 分钟。

Spring Boot + Lettuce连接 Redis 集群(单机/主备/ProxyCluster)

1. 项目依赖

在项目 pom.xml 中添加必要的依赖项:

org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-redis

2. Redis 配置

application.properties 文件中配置 Redis 连接信息:

spring.redis.host=host
spring.redis.database=0
spring.redis.password=pwd
spring.redis.port=port
# 连接超时时间
spring.redis.timeout=1000

3. Redis 连接池配置

为了提高连接效率,建议使用连接池:

# 连接池最大连接数(使用负值表示没有限制)
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
# 间隔时间(毫秒)进行连接池的空闲连接清理
spring.redis.lettuce.pool.time-between-eviction-runs=2000

4. Redis 连接配置类

创建自定义的 Redis 连接配置类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.LettuceConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedisConfiguration {
@Autowired
private LettuceConnectionFactory lettuceConnectionFactory;
@Bean
public RedisTemplate
redisTemplate() {
RedisTemplate
template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory);
// 使用 Jackson2JsonRedisSerializer 替换默认的序列化方式
Jackson2JsonRedisSerializer
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();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}

5. Redis 操作工具类

创建一个 Redis 操作工具类:

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisUtil {
private RedisTemplate
redisTemplate;
public RedisUtil(RedisTemplate
redisTemplate) {
this.redisTemplate = redisTemplate;
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

6. 测试控制器

创建一个测试控制器类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloRedisController {
@Autowired
private RedisUtil redisUtil;
@RequestMapping("/set")
@ResponseBody
public String setParams(String name) {
redisUtil.set("name", name);
return "success";
}
@RequestMapping("/get")
@ResponseBody
public String getParams(String name) {
System.out.println("获取数据 - " + name);
return redisUtil.get(name).toString();
}
}

7. Redis 集群配置

application.properties 中添加集群配置:

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

8. Redis 集群连接配置类

创建一个自定义的 Redis 集群连接配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.LettuceConnectionFactory;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class RedisClusterConfiguration {
@Bean
public LettuceConnectionFactory lettuceConnectionFactory(
String clusterNodes,
String password,
Integer maxRedirects,
Integer period,
Integer timeout) {
List
listNodes = new ArrayList<>();
String[] nodes = clusterNodes.split(",");
for (String node : nodes) {
String[] ipPort = node.split(":");
RedisNode redisNode = new RedisNode(ipPort[0], Integer.parseInt(ipPort[1]));
listNodes.add(redisNode);
}
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
clusterConfig.setClusterNodes(listNodes);
clusterConfig.setPassword(password);
clusterConfig.setMaxRedirects(maxRedirects);
ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
.enablePeriodicRefresh(Duration.ofSeconds(period))
.enableAllAdaptiveRefreshTriggers()
.build();
ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
.timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(timeout)))
.topologyRefreshOptions(topologyRefreshOptions)
.build();
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofSeconds(timeout))
.readFrom(ReadFrom.REPLICA_PREFERRED)
.clientOptions(clusterClientOptions)
.build();
LettuceConnectionFactory factory = new LettuceConnectionFactory(clusterConfig, clientConfig);
return factory;
}
}

9. Redis 集群操作工具类

创建一个 Redis 集群操作工具类:

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisClusterUtil {
private RedisTemplate
redisTemplate;
public RedisClusterUtil(RedisTemplate
redisTemplate) {
this.redisTemplate = redisTemplate;
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

10. 使用说明

1. 单机/主备/Proxy 集群

  • 如果只是单机 Redis 或 Redis 主备集群,直接使用单连接方式即可。
  • 如果需要通过 Proxy 软件(如 Redis Sentinel)实现高可用性,同样可以使用单连接方式。

2. 集群方式

  • 单连接方式:适用于 Redis 单机和简单的主备集群。
  • 连接池方式:适用于复杂的 Redis 集群场景(如 Redis Cluster、Redis Sentinel 等),可以实现连接池的使用,提升性能和可用性。

3. 参数说明

  • spring.redis.host:Redis 的主机地址或域名。
  • spring.redis.port:Redis 的端口号。
  • spring.redis.timeout:连接 Redis 的超时时间(默认 500ms)。
  • 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:连接池的最大等待时间(默认 5000ms)。
  • spring.redis.lettuce.pool.time-between-eviction-runs:连接池空闲连接清理的时间间隔(默认 2000ms)。

4. 高级配置

  • spring.redis.lettuce.cluster.refresh.period:集群拓扑刷新的周期(默认 60秒)。
  • spring.redis.lettuce.cluster.refresh.adaptive:是否启用自适应拓扑刷新(默认 true)。
  • spring.redis.lettuce.cluster.max-redirects:最大重定向次数(默认 3)。

5. 注意事项

  • 连接池配置:根据业务需求合理设置连接池的最大连接数、空闲连接数和等待时间等参数,避免因连接耗尽或超时导致服务故障。
  • 超时设置:默认连接超时为 500ms,建议根据实际网络环境进行调整。
  • 序列化方式:默认使用 Jackson2JsonRedisSerializer,可根据业务需求选择其他序列化方式。
  • 性能优化:如果需要高并发访问,建议使用连接池,并根据实际负载调整连接池参数。

通过以上配置,您可以轻松实现 Spring Boot + Lettuce 连接 Redis 集群(单机/主备/ProxyCluster)的高效管理。

转载地址:http://dxqfk.baihongyu.com/

你可能感兴趣的文章
Objective-C实现检测U盘的插入与拔出 (附完整源码)
查看>>
Objective-C实现检测列表中的循环算法(附完整源码)
查看>>
Objective-C实现检测耳机插拔功能(附完整源码)
查看>>
Objective-C实现模拟键盘鼠标(附完整源码)
查看>>
Objective-C实现模板方法模式(附完整源码)
查看>>
Objective-C实现欧几里得距离(附完整源码)
查看>>
Objective-C实现欧几里得距离(附完整源码)
查看>>
Objective-C实现欧拉路径和欧拉回路算法(附完整源码)
查看>>
Objective-C实现正向CMDShell(附完整源码)
查看>>
Objective-C实现正数num使用递归找到它的二进制算法(附完整源码)
查看>>
Objective-C实现水波纹显示效果(附完整源码)
查看>>
Objective-C实现求 1 到 20 的所有数整除的最小正数算法 (附完整源码)
查看>>
Objective-C实现求1000以内的全部亲密数(附完整源码)
查看>>
Objective-C实现求a的逆元x(附完整源码)
查看>>
Objective-C实现求squareDifference平方差算法 (附完整源码)
查看>>
Objective-C实现求一个数的位数之和算法(附完整源码)
查看>>
Objective-C实现求一个数的因子算法(附完整源码)
查看>>
Objective-C实现求一组数字的平均值算法(附完整源码)
查看>>
Objective-C实现求两个数组的中位数算法(附完整源码)
查看>>
Objective-C实现求两点间距离(附完整源码)
查看>>