springboot 引入lettuce 自定义redis地址

本文介绍了如何在SpringBoot项目中配置和使用Redis,包括引入依赖、设置Redis连接参数、使用LettuceConnectionFactory和RedisTemplate,以及序列化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;


@Configuration //配置类
@Slf4j
public class CacheRedisTemplateConfig{


    private String host="127.0.0.1";

    private Integer database=1;

    private Integer port=6379;

    private String password="12345678";

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {

        RedisTemplate<String, Object>  template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(lettuceConnectionFactory());
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key 都使用String 序列化方式
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        template.setValueSerializer(genericJackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    public LettuceConnectionFactory lettuceConnectionFactory(){
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);
        config.setPort(port);
        config.setPassword(RedisPassword.of(password));
        config.setDatabase(database);
        SocketOptions socketOptions = SocketOptions.builder().connectTimeout(Duration.ofMillis(600)).build();
        ClientOptions standaloneClientOptions = ClientOptions.builder()
                .socketOptions(socketOptions)
                .build();
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(10);
        genericObjectPoolConfig.setMinIdle(5);
        genericObjectPoolConfig.setMaxTotal(100);
        genericObjectPoolConfig.setMaxWaitMillis(5000);
        genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(1000);
        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(1))
                .shutdownTimeout(Duration.ofMillis(100))
                .poolConfig(genericObjectPoolConfig)
                .clientOptions(standaloneClientOptions)
                .build();
        LettuceConnectionFactory lettuceConnectionFactory =  new LettuceConnectionFactory(config,clientConfig);
        lettuceConnectionFactory.afterPropertiesSet();
        return lettuceConnectionFactory;
    }
}

<think>好的,我现在需要帮助用户解决在Spring Boot项目中连接云服务器上的Redis的问题。首先,我得回忆一下相关的配置步骤,确保自己记得正确。用户需要的是配置教程和示例,所以应该详细说明每一步,并提供代码示例。 首先,Spring Boot连接Redis通常使用Spring Data Redis,这个模块简化了配置。用户提到的是云服务器上的Redis,所以需要注意云服务器的IP地址、端口、密码以及可能的防火墙设置。比如,云服务器的Redis可能需要开放相应的端口,比如默认的6379,或者如果用了SSL,可能端口不同。此外,云服务商如阿里云、AWS等可能有特定的安全组设置,需要用户自己去配置允许访问,这点可能需要提醒用户检查。 接下来是项目的依赖部分。用户需要添加Spring Boot Data Redis的starter依赖,可能还需要连接池,比如Lettuce或者Jedis。现在Spring Boot默认使用Lettuce,但用户也可以选择Jedis。在pom.xml或build.gradle中添加依赖是第一步。比如Maven的话,添加spring-boot-starter-data-redis。 然后是配置文件,通常是application.properties或application.yml。需要设置redis.host为云服务器的公网IP,端口如果没改的话是6379,如果有密码的话需要配置password。此外,如果云服务商的Redis需要SSL连接,可能需要额外的配置,比如设置ssl=true,或者调整其他参数。例如: spring.data.redis.host=你的云服务器IP spring.data.redis.port=6379 spring.data.redis.password=你的密码 如果使用连接池,可能需要配置连接池的参数,比如最大连接数、超时时间等。例如: spring.data.redis.lettuce.pool.max-active=8 spring.data.redis.lettuce.pool.max-idle=8 spring.data.redis.lettuce.pool.min-idle=0 spring.data.redis.lettuce.pool.max-wait=-1ms 接下来,可能需要提供一个配置类,特别是如果需要自定义序列化方式或者其他RedisTemplate的设置。比如,默认的RedisTemplate使用JdkSerializationRedisSerializer,可能用户想换成Jackson或者String序列化器。配置类可能如下: @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } 然后,用户可能需要测试连接是否成功。可以编写一个测试类,注入StringRedisTemplate或RedisTemplate,执行一个简单的操作,比如set和get。例如: @SpringBootTest public class RedisTest { @Autowired private StringRedisTemplate stringRedisTemplate; @Test public void testConnection() { stringRedisTemplate.opsForValue().set("testKey", "Hello Redis"); String value = stringRedisTemplate.opsForValue().get("testKey"); System.out.println(value); // 应该输出 Hello Redis } } 另外,需要提醒用户检查云服务器安全组的入站规则,确保允许来自应用服务器IP的6379端口访问。如果Redis配置了bind,可能需要注释掉或者允许外部连接,可能需要修改redis.conf文件中的bind 127.0.0.1改为bind 0.0.0.0,或者添加相应的IP。同时,关闭保护模式protected-mode no,并设置密码requirepass。 如果连接出现问题,用户可能会遇到超时或者连接拒绝。这时候需要检查防火墙设置,云服务商的安全组,以及Redis的配置是否正确。可能还需要使用telnet或者nc命令测试端口是否可达。 最后,结合用户提供的引用,特别是引用[3]提到了Spring Boot配合Redis实现LRU-K策略,可能用户后续有缓存策略的需求,可以在相关问题里提及,或者作为扩展内容。 现在需要确保回答的结构清晰,分步骤说明,并提供代码示例。同时,用户提到的引用中的内容,比如引用[3]可以自然地引用到相关问题中,比如关于缓存策略的优化。</think>### Spring Boot连接云端Redis配置教程 #### 步骤1:添加依赖 在`pom.xml`中引入Spring Data Redis和连接池依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` #### 步骤2:配置连接参数 在`application.properties`中设置Redis云服务器信息: ```properties # 云服务器Redis配置 spring.data.redis.host=云服务器公网IP spring.data.redis.port=6379 spring.data.redis.password=your_password # 连接池参数(可选) spring.data.redis.lettuce.pool.max-active=8 spring.data.redis.lettuce.pool.max-idle=8 ``` #### 步骤3:自定义序列化配置(可选) 创建配置类`RedisConfig.java`,指定键值序列化方式: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` #### 步骤4:测试连接 编写测试用例验证连接: ```java @SpringBootTest public class RedisConnectionTest { @Autowired private RedisTemplate<String, String> redisTemplate; @Test public void testSetAndGet() { redisTemplate.opsForValue().set("test", "success"); String value = redisTemplate.opsForValue().get("test"); System.out.println("获取值: " + value); // 应输出"success" } } ``` #### 关键注意事项 1. **安全组配置**:确保云服务器开放6379端口(或自定义端口)的入站规则[^3] 2. **Redis配置修改**: - 修改`redis.conf`中的`bind 0.0.0.0` - 设置`protected-mode no` - 添加`requirepass your_password` 3. **连接超时处理**:可在配置中添加`spring.data.redis.timeout=5000`(单位:毫秒)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值