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,
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Slf4j public 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
,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| 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;
@Configuration public class RedisConfig {
@Bean @ConditionalOnSingleCandidate(RedisConnectionFactory.class) public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate(); template.setConnectionFactory(lettuceConnectionFactory); 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); template.setDefaultSerializer(jacksonSeial); return template; } }
|
@ConditionalOnSingleCandidate 注解
Spring容器中是否存在且只存在一个对应的实例,或者虽然有多个但 是指定首选的Bean生效
最后经测试