暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Redis集群与Lettuce

原创 soul0202 2023-10-26
786

Redis官方推荐的java客户端三大客户端Jedis、lettuce、Redisson

lettuce、jedis、Redisson 三者比较:
jedis提供全面的指令支持,在多线程环境下是非线程安全的,性能比较差;

lettuce的连接是基于Netty的,连接实例可以在多个线程间并发访问;

Jedis 和 lettuce 是比较纯粹的 Redis 客户端,几乎没提供什么高级功能;

Redisson实现了分布式和可扩展的Java数据结构,和Jedis相比,功能较为简单,不支持字符串操作,不支持排序、事务、管道、分区等Redis特性。Redisson的宗旨是促进使用者对Redis的关注分离,从而让使用者能够将精力更集中地放在处理业务逻辑上。如果需要分布式锁,分布式集合等分布式的高级特性,添加Redisson结合使用,因为Redisson本身对字符串的操作支持很差。

Jedis 的性能比较差,所以如果你不需要使用 Redis 的高级功能的话,优先推荐使用 lettuce。

使用建议
建议:lettuce + Redisson

在spring boot2之后,redis连接默认就采用了lettuce。

就想 spring 的本地缓存,默认使用Caffeine一样,

这就一定程度说明了,lettuce 比 Jedis在性能的更加优秀。

Redis单例配置
redis:
password: xxx
host: xxx
port: 6379
lettuce: #lettuce客户端配置
pool: #连接池配置
max-active: 500 # 连接池最大连接数(使用负值表示没有限制) 默认 8
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-idle: 10 # 连接池中的最大空闲连接 默认 8
min-idle: 5 # 连接池中的最小空闲连接 默认 0
timeout: 3000 # 连接超时时间(毫秒)
Redis集群配置
redis:
password: xxx
cluster:
#集群配置
nodes: xxx:6379,xxx:6379,xxx:6379
max-redirects: 3
lettuce: #lettuce客户端配置
pool: #连接池配置
max-active: 500 # 连接池最大连接数(使用负值表示没有限制) 默认 8
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-idle: 10 # 连接池中的最大空闲连接 默认 8
min-idle: 5 # 连接池中的最小空闲连接 默认 0
timeout: 3000 # 连接超时时间(毫秒)
Redis和lettuce配置
@Configuration
public class RedisConfig {

/**
* retemplate相关配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(@Qualifier("lettuceConnectionFactory") LettuceConnectionFactory factory) {

RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);

//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);

// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());

// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();

return template;
}

@Bean
public DefaultClientResources lettuceClientResources() {
return DefaultClientResources.create();
}

@Bean("lettuceConnectionFactory")
public LettuceConnectionFactory lettuceConnectionFactory(RedisProperties redisProperties, ClientResources clientResources, GenericObjectPoolConfig redisPoolConfig) {

ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
//按照周期刷新拓扑
.enablePeriodicRefresh(Duration.ofSeconds(10))
//根据事件刷新拓扑
.enableAllAdaptiveRefreshTriggers()
.build();

ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
//redis命令超时时间,超时后才会使用新的拓扑信息重新建立连接
.autoReconnect(true)
.cancelCommandsOnReconnectFailure(false)
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.DEFAULT)
.pingBeforeActivateConnection(true)
.timeoutOptions(TimeoutOptions.enabled(redisProperties.getTimeout()))
.topologyRefreshOptions(topologyRefreshOptions)
.socketOptions(SocketOptions.builder().connectTimeout(redisProperties.getTimeout()).keepAlive(true).build())
.build();

LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.clientResources(clientResources)
.clientOptions(clusterClientOptions)
.commandTimeout(redisProperties.getTimeout())
.shutdownTimeout(redisProperties.getLettuce().getShutdownTimeout())
.poolConfig(redisPoolConfig)
.build();

if(StringUtils.isEmpty(redisProperties.getCluster())){
//单机
RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(redisProperties.getHost(),redisProperties.getPort());
redisConfiguration.setDatabase(redisProperties.getDatabase());
redisConfiguration.setPassword(redisProperties.getPassword());

LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisConfiguration, clientConfig);
lettuceConnectionFactory.afterPropertiesSet();
lettuceConnectionFactory.setValidateConnection(false);

return lettuceConnectionFactory;
}else {
//集群
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
clusterConfig.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
clusterConfig.setPassword(RedisPassword.of(redisProperties.getPassword()));

LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(clusterConfig, clientConfig);
lettuceConnectionFactory.afterPropertiesSet();
lettuceConnectionFactory.setValidateConnection(false);

return lettuceConnectionFactory;
}
}

/**
* Redis连接池配置</b>
*/
@Bean
public GenericObjectPoolConfig redisPoolConfig(RedisProperties redisProperties) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
poolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
poolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
poolConfig.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().toMillis());
poolConfig.setTimeBetweenEvictionRunsMillis(100);
return poolConfig;
}

}

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论