redis:Unable to connect to localhost:6379

cccs7 Lv5

redis:Unable to connect to localhost:6379

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

image-20230331090803733


报错显示 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());
}
}

输出结果如下:

image-20230331091750972


我查阅其他资料并没有发现与我类似的情况,因为我在 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;

/**
* redis 配置
*
* @author cs7eric
* @date 2023/03/30
*/
@Configuration
public 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的序列化方式为JSON
template.setDefaultSerializer(jacksonSeial);
return template;
}
}

@ConditionalOnSingleCandidate 注解

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


最后经测试

image-20230331091931592

  • Title: redis:Unable to connect to localhost:6379
  • Author: cccs7
  • Created at: 2023-03-31 09:04:22
  • Updated at: 2023-06-29 23:13:38
  • Link: https://blog.cccs7.icu/2023/03/31/redisUnable-to-connect-to-localhost6379/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments
On this page
redis:Unable to connect to localhost:6379