解决 Error creating bean with name 'redisConnectionFactory'问题,使spring boot跳过redis连接后启动的方法

2022-06-23 09:38:19

场景:

今天在开发环境,启动服务做测试的时候,发现一个问题:

那就是开发环境没有安装redis,导致spring boot无法启动

无法启动的原因是:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConnectionConfiguration.class]: Invocation of init method failed; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect

需求:

由于我们做了服务降级机制,如果redis不能使用,那么就使用mysql。

我们想让spring boot没有连接redis,也可以启动。

另外一种使用场景是:我只想测试与redis无交互的某些功能

思路:

就是不使用spring boot的redis自动装配,redisTemplate自动注入的时候,require=false

解决方法:

1. 在application.properties中加入

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

2.自定义了restTemplate,

这里使用了@ConditionalOnBean(RedisConnectionFactory.class)

@Configurationpublic classRedisConfig{@Bean

    @ConditionalOnBean(RedisConnectionFactory.class)publicRedisTemplate<String,String>redisTemplate(RedisConnectionFactoryfactory) {RedisTemplate<String,String>redisTemplate =newRedisTemplate();redisTemplate.setConnectionFactory(factory);RedisSerializer<String>stringRedisSerializer =newStringRedisSerializer();redisTemplate.setKeySerializer(stringRedisSerializer);

        returnredisTemplate;}

}

3. service中使用

@Autowired(required=false)privateRedisTemplateredisTemplate;

这样,系统就可以正常启动了。

另外一些场景:

在使用spring cache的redis的时候,

在使用spring session的redis的时候

如果没有redis服务,那么是不是spring boot也是无法启动的?

参考:Disable Redis AutoConfig in spring boot when testing

  • 作者:const伐伐
  • 原文链接:https://blog.csdn.net/u013905744/article/details/100737481
    更新时间:2022-06-23 09:38:19