SpringBoot使用Lettuce集成redis

1、引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

这里要注意的是Lettuce是SpringBoot 2.x后才使用的,之前使用的是Jedis作为连接池,请注意自己项目的SpringBoot版本。

2、RedisConfig配置类

package controller;

import io.lettuce.core.ClientOptions;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;

@Configuration
public class RedisConfig extends CachingConfigurerSupport{

    @Resource
    private RedisProperties redisProperties;

    public GenericObjectPoolConfig<?> genericObjectPoolConfig(RedisProperties.Pool properties) {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(properties.getMaxActive());
        config.setMaxIdle(properties.getMaxIdle());
        config.setMinIdle(properties.getMinIdle());
        if (properties.getTimeBetweenEvictionRuns() != null) {
            config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
        }
        if (properties.getMaxWait() != null) {
            config.setMaxWaitMillis(properties.getMaxWait().toMillis());
        }
        return config;
    }

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

    @Bean(destroyMethod = "destroy")
    public LettuceConnectionFactory lettuceConnectionFactory(ClientResources clientResources) {

        //开启 自适应集群拓扑刷新和周期拓扑刷新
        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                // 开启全部自适应刷新
                .enableAllAdaptiveRefreshTriggers() // 开启自适应刷新,自适应刷新不开启,Redis集群变更时将会导致连接异常
                // 自适应刷新超时时间(默认30秒)
                //默认关闭开启后时间为30秒
                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15))
                // 开周期刷新
                // 默认关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60  .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
                .enablePeriodicRefresh(Duration.ofSeconds(15))
                .build();

        // https://github.com/lettuce-io/lettuce-core/wiki/Client-Options
        ClientOptions clientOptions = ClusterClientOptions.builder()
                .topologyRefreshOptions(clusterTopologyRefreshOptions)
                .build();

        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .clientResources(clientResources)
                .poolConfig(genericObjectPoolConfig(redisProperties.getLettuce().getPool()))
                .readFrom(ReadFrom.MASTER_PREFERRED)
                .clientOptions(clientOptions)
                //默认RedisURI.DEFAULT_TIMEOUT 60
                .commandTimeout(redisProperties.getTimeout())
                .build();

        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
        clusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
     // clusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());

        return new LettuceConnectionFactory(clusterConfiguration, clientConfig);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        StringRedisSerializer serializer = new StringRedisSerializer();
        redisTemplate.setDefaultSerializer(serializer);
        redisTemplate.setKeySerializer(serializer);
        redisTemplate.setValueSerializer(serializer);

        /**必须执行这个函数,初始化RedisTemplate*/
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

3、yml文件配置

spring:
  redis:
    cluster:
      nodes[0]: 10.111.111.111:6379
    lettuce:
##Redis服务器连接密码(默认为空)
#      password:
##连接池最大连接数(使用负值表示没有限制)
      pool:
        max-active: 8
#连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
#连接池中的最大空闲连接
        max-idle: 8
#连接池中的最小空闲连接
        min-idle: 0
#连接超时时间(毫秒)
    timeout: 30000

4、遇到的几个小坑

    错误1:

template not initialized; call afterPropertiesSet() before using it

 解决方法就是,使用redisTemplate的时候,采用@Autowired注入的方式,不要直接new 出来

    

   错误2:

ERR This instance has cluster support disabled

 这个是因为redis没有开启集群模式,在安装redis的目录找到redis配置文件redis.conf,里面会找到配置 

# cluster-enabled yes

把注释去掉,然后重启就可以了。

  错误3:

Cannot determine a partition to read for slot

这个是因为开启redis集群后,但是slot未分配,解决方式是在redis服务器上执行:

redis-cli --cluster fix 10.111.111.111:6379 -a 123456(密码使用自己配置的)

 中途弹出Fix these slots by covering with a random node? (type 'yes' to accept):

输入yes即可。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
狂神SpringBoot集成Redis可以通过添加Spring Boot的依赖来实现。在pom.xml文件中,可以添加以下依赖来集成Redis: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这个依赖会引入Spring Data Redis库,它封装了对Redis的操作,支持多种操作方式,包括JPA、JDBC、MongoDB以及Redis。在Spring Boot 2.x版本之后,底层替换了原来的Jedis为LettuceLettuce采用netty作为高性能网络框架,并支持异步请求和多线程共享实例,不存在线程不安全的情况。与Jedis相比,Lettuce更加安全可靠。 在application.yml配置文件中,可以通过配置以spring.redis开头的属性来设置Redis的连接信息,例如host、password等。这些配置会被Spring Boot自动加载并注入到应用程序中。 通过以上步骤,你就可以使用Spring Boot集成Redis,并进行各种操作,包括读取、写入、删除数据等。这样可以方便地在Spring Boot应用程序中使用Redis来实现缓存、分布式锁等功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot狂神26-(redis集成)](https://blog.csdn.net/weixin_45433031/article/details/119842921)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值