Redis集群和Lettuce 配置

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;
    }
}
  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,使用 Lettuce 连接 Redis 时,可以通过自适应配置来适配单机版 Redis集群Redis。自适应配置是指,当配置文件中的属性值符合某种特定的格式时,Lettuce 会自动识别当前 Redis 环境是否为集群版,并自动进行相应的连接池配置。 具体来说,当 `spring.redis.host` 属性为空时,Lettuce 将会按照集群Redis 的方式进行连接。此时,需要在 `spring.redis.cluster.nodes` 属性中指定 Redis 集群中所有节点的地址和端口号,以逗号分隔。例如: ```properties # Redis 自适应集群版连接池配置 spring.redis.host= spring.redis.port= spring.redis.password=your_password spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381 spring.redis.timeout=1000 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 ``` 当 `spring.redis.host` 属性不为空时,Lettuce 将会按照单机版 Redis 的方式进行连接。此时,只需要在 `spring.redis.host` 和 `spring.redis.port` 属性中指定 Redis 服务器的地址和端口号即可。例如: ```properties # Redis 自适应单机版连接池配置 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=your_password spring.redis.timeout=1000 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 ``` 需要注意的是,当 `spring.redis.host` 属性为空时,必须同时指定 `spring.redis.cluster.nodes` 属性,否则会抛出异常。此外,当使用自适应配置连接集群Redis 时,需要在 `pom.xml` 文件中添加 Lettuce 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>5.3.4.RELEASE</version> </dependency> ``` 以上就是在 Spring Boot 中使用 Lettuce 进行自适应配置连接单机版 Redis集群Redis 的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值