Spring Boot 使用Redis拒绝连接以及获取不到连接池

本文介绍了解决SpringBoot项目中Redis连接失败及缓存配置问题的方法。包括修改redis.conf配置、解决防火墙问题、配置SpringBoot读取外部属性文件、解决注入冲突等步骤。

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

使用环境

  1. 使用spring boot构建上层服务项目
  2. redis缓存相关方法写到公共工具类,被上层服务依赖 common-utils
  3. redis是安装在本地虚拟机中

启动服务,首先程序报错为拒绝连接:

然后使用本地可视化工具进行测试连接,显示同样的错误
connection refused

解决方法:

  1. 首先在redis.conf中注释掉bind 127.0.0.1这一行,其意思是只允许本地访问连接,其他Ip都将被拒绝.
  2. 如果第一步操作过后,依然拒绝连接,可能为redis部署机器的防火墙没有关闭或者网络不通,进行如下操作:

2.1. 首先检查自己的网络,是否可以ping通
2.2. 检查端口 netstat -tunlp |grep 6379
tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 3227/redis-server *,查看结果也是ok的.
2.3 服务器防火墙的问题,关了防火墙试下:
systemctl stop firewalld.service(我的远程机器是centos7)

补充:
systemctl stop firewalld.service #停止firewall
systemctl disable firewalld.service #禁止firewall开机启动
执行下面这段命令就可以开放6379端口了
firewall-cmd --zone=public --add-port=6379/tcp --permanent

至此本地可视化工具已经连接可用;

启动spring boot程序,无法获取到RedisTemplate

2438927-0ddc1ae83dd1e926.png

jar包使用@Configuration配置redis缓存
代码如下:

@Configuration
@EnableCaching
@PropertySource("classpath:RedisConfig.properties")
public class RedisConfig extends CachingConfigurerSupport{
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }
    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

属性文件在common-util包中,RedisConfig.properties内容如下:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.22.111
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)

开始怀疑spring boot不会自动扫描jar包中的@Configuration注解,测试过后,这个是完全可以的;
接下来开始调试,发现redis使用的是默认连接(127.0.0.1:6379)并没有读取到我的属性文件,原来spring boot不能默认读取jar包中的属性文件,需要我们手工指定装载进来:
@Configuration注解那里加上@PropertySource("classpath:RedisConfig.properties")

接下来问题又出现了:

Description:
Field template in org.pekxxoo.redis.RedisUtil required a single bean, but 2 were found:
    - redisTemplate: defined by method 'redisTemplate' in class path resource [org/pekxxoo/redis/RedisConfig.class]
    - stringRedisTemplate: defined by method 'stringRedisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConfiguration.class]

看说明,可以知道,是因为@Autowired在注入时,是匹配类型的,如果存在两个一个类型的实例时就会报错,报错信息指出,一个redisTemplate是在我的RedisConfig.class中配置的,另一个是RedisAutoConfiguration中进行声明的,因此两种解决方案:

  1. 在启动类处加上注解:@EnableAutoConfiguration(exclude = RedisAutoConfiguration.class)关闭自动注入配置;
  2. 在RedisUtil.class注入时结合@Qualifier("")注解:
@Qualifier("redisTemplate")
@Autowired
private RedisTemplate<String,String> template;

至此spring boot 结合redis缓存终于启动成功;

<think>好的,我需要帮助用户在Spring Boot中配置Lettuce连接池连接Redis 2.7.2。首先,我需要回顾一下用户提供的引用内容,看看有没有相关的配置信息。 用户引用了application.properties中的配置,比如spring.redis.host、port、database等,还有Lettuce连接池的参数,如max-active、max-wait、max-idle和min-idle。这些都是在配置文件中设置的基本参数。另外,用户提到需要自定义配置类来改变序列化方式,默认是JDK,而他们希望使用JSON。引用3提到了Redis的自定义配置类,这可能涉及到创建@Configuration类,并配置RedisTemplate或LettuceConnectionFactory。 接下来,我需要确保步骤正确。首先,添加依赖项,应该是spring-boot-starter-data-redis,这个会自动引入Lettuce。然后,在application.properties或application.yml中配置连接信息和连接池参数。用户给的例子是application.properties中的配置,所以需要指导用户如何正确填写这些属性。 然后,可能需要自定义配置类,特别是如果用户需要更改默认的序列化方式。引用3指出默认使用JDK序列化,而用户可能想要JSON,所以需要配置RedisTemplate的序列化器,比如使用Jackson2JsonRedisSerializer。 另外,用户提到@EnableCaching和@Cacheable的使用,但这个问题主要是关于连接池配置,所以可能不需要深入讨论缓存注解,但需要确保配置正确,以便连接池生效。 需要注意用户提到的Redis版本是2.7.2,但通常Spring Boot的版本会更重要,因为不同版本的Spring Boot可能对Redis客户端的支持不同。不过用户的问题标题提到的是Redis 2.7.2,可能是指Spring Boot的某个版本?或者可能是笔误?可能需要澄清,但根据上下文,用户可能是指Spring Boot 2.7.2版本,对应的Spring Data Redis可能使用Lettuce作为默认客户端。 另外,引用4和5中的Redis命令和数据类型可能不直接相关,但需要确保配置正确后,这些数据类型能被正确处理。 总结步骤应该是: 1. 添加依赖:spring-boot-starter-data-redis 2. 配置application.properties中的连接参数和Lettuce连接池参数 3. 创建配置类,设置RedisTemplate的序列化方式(可选,但推荐) 4. 测试配置是否生效 需要确保在配置连接池参数时,属性名前缀正确,比如spring.redis.lettuce.pool.*。同时,提醒用户如果使用连接池,可能需要调整max-active、max-idle等参数以适应实际需求。 可能的问题点:是否需要在配置类中显式配置LettuceConnectionFactory,或者是否通过application.properties自动配置即可。根据引用2中的描述,只要配置了连接参数和连接池属性,Spring Boot会自动配置Lettuce连接池,所以可能不需要额外的Java配置,除非需要自定义。 但若需要自定义序列化方式,就需要通过@Bean来覆盖默认的RedisTemplate,如引用3所述。这时候可能需要编写配置类,设置key和value的序列化器为Jackson2JsonRedisSerializer或其他JSON序列化器。 最后,生成相关问题,可能需要包括如何测试连接池是否生效、如何选择连接池参数、序列化方式的选择等。</think>在Spring Boot中配置Lettuce连接池连接Redis 2.7.2的步骤如下: ### 1. 添加依赖 在`pom.xml`中引入Spring Data Redis依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` ### 2. 配置连接参数 在`application.properties`中设置Redis服务器信息和Lettuce连接池参数: ```properties # Redis基础配置 spring.redis.host=192.168.153.136 spring.redis.port=6379 spring.redis.database=0 spring.redis.timeout=1800000 # Lettuce连接池配置 spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0 ``` 参数说明: - `max-active`:连接池最大连接数(默认-1无限制) - `max-wait`:获取连接的最大等待时间(默认-1无限制) - `max-idle`:最大空闲连接数 - `min-idle`:最小空闲连接数[^1] ### 3. 自定义序列化配置(可选) 若需将默认JDK序列化改为JSON,创建配置类: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 设置JSON序列化器 Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); template.setHashValueSerializer(serializer); return template; } } ``` 此配置使用`Jackson2JsonRedisSerializer`替代默认的JDK序列化[^3]。 ### 4. 测试使用 通过`RedisTemplate`直接操作Redis: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void setValue(String key, Object value) { redisTemplate.opsForValue().set(key, value); } ``` ### 注意事项 1. 确保Redis服务器已启动且网络可达 2. 若使用`@Cacheable`注解,需在启动类添加`@EnableCaching` 3. Lettuce是Spring Boot 2.x默认的Redis客户端,无需额外配置[^2] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值