SpringBoot集成Redis触发RedisConnectionException连接失败求助
Redis连接失败问题排查与解决
问题根源
错误栈的核心原因是:java.lang.IllegalArgumentException: 主机包含端口: {hostName}:6379,说明你配置的Redis主机地址中已经附带了端口号,但配置类又单独设置了port=6379,导致Lettuce客户端尝试连接时出现参数冲突。
解决步骤
1. 修正Redis主机配置
打开application.yml,确保spring.data.redis.host仅填写纯主机地址,不要附带端口号:
spring: application: name: "application-name" data: redis: host: redis.example.com # 示例:只填主机域名/IP,不要加:6379 port: 6379 username: {myUsername} password: {myPassword} ssl: enabled: true
2. 简化配置逻辑(可选但推荐)
Spring Boot自带了官方的RedisProperties(org.springframework.boot.autoconfigure.data.redis.RedisProperties),无需自定义RedisProperties类,直接使用官方类可以避免配置读取错误,同时支持更多默认配置项:
修改你的RedisConfigurationBuilder:
@Configuration @RequiredArgsConstructor public class RedisConfigurationBuilder { // 使用官方自带的RedisProperties private final org.springframework.boot.autoconfigure.data.redis.RedisProperties redisProperties; @Bean public RedisConnectionFactory redisConnectionFactory() { try { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(redisProperties.getHost()); redisStandaloneConfiguration.setPort(redisProperties.getPort()); // Redis 6.0+才支持用户名,空值时跳过设置 if (StringUtils.hasText(redisProperties.getUsername())) { redisStandaloneConfiguration.setUsername(redisProperties.getUsername()); } redisStandaloneConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword())); // 动态读取配置中的SSL开关,不要硬编码 LettuceClientConfiguration.LettuceClientConfigurationBuilder clientConfigBuilder = LettuceClientConfiguration.builder(); if (redisProperties.isSsl()) { clientConfigBuilder.useSsl(); } clientConfigBuilder.commandTimeout(Duration.ofSeconds(2)); return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfigBuilder.build()); } catch (Exception e) { throw new RuntimeException("Redis配置失败", e); } } @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer()); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } }
然后删除你自定义的RedisProperties类,避免和官方类冲突。
3. 极端简化:使用Spring Boot自动配置(可选)
如果你的Redis是单实例、无需特殊序列化或连接配置,甚至可以直接删除自定义的RedisConfigurationBuilder,Spring Boot会自动根据application.yml中的配置生成RedisConnectionFactory和RedisTemplate,只需确保配置项正确即可。
内容的提问来源于stack exchange,提问作者AndreaCavallo.class
相关产品推荐
相关产品推荐

