redis:Unable to connect to localhost:6379

我整合 springboot 与 redis 时,运行报 Unable to connect to localhost:6379 错误,但是我 application.yaml 中配置的 host 为 Linux 虚拟机的 ip,所以该属性并未被装配

报错显示 unable to connect to localhost:6379,连接的为 Windows 主机的 redis , 我又写了一个demo,

@Slf4jpublic class TestJedis {public static void main(String[] args) {Jedis jedis = new Jedis("192.168.21.135", 6379);jedis.auth("xxxxx");log.info("redis conn status:{}","连接成功");log.info(jedis.ping());jedis.set("k1222","2222");log.info(jedis.get("k1222"));log.info("{}", jedis.getConnection());}}

输出结果如下:

我查阅其他资料并没有发现与我类似的情况,因为我在 RedisConfig 中 自己装配了 RedisTemplate ,所以可能是在配置类没有 装配 applicaiton.yml 中的 spring.redis 属性,我又重写 了 RedisConfig,如下:

package com.cs7eric.eatmore.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;/** * redis 配置 * * @author cs7eric * @date 2023/03/30 */@Configurationpublic class RedisConfig {@Bean@ConditionalOnSingleCandidate(RedisConnectionFactory.class)public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate();template.setConnectionFactory(lettuceConnectionFactory);// 使用JSON格式序列化对象,对缓存数据key和value进行转换Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);// 解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jacksonSeial.setObjectMapper(om);// 设置RedisTemplate模板API的序列化方式为JSONtemplate.setDefaultSerializer(jacksonSeial);return template;}}

@ConditionalOnSingleCandidate 注解

Spring容器中是否存在且只存在一个对应的实例,或者虽然有多个但 是指定首选的Bean生效

最后经测试