连接虚拟机上的redis报错Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 192.168.240.105 :6379] with root cause java.net.UnknownHostException: 192.168.240.105
时间: 2025-06-01 07:18:35 浏览: 30
### Redis连接失败问题分析与解决
在Spring Boot项目中,当尝试连接虚拟机上的Redis时出现`io.lettuce.core.RedisConnectionException`或`java.net.UnknownHostException`异常,通常是由以下原因引起的:
1. **Redis服务未启动**:确保虚拟机上的Redis服务已经正常启动并正在监听指定的端口[^3]。
2. **网络配置问题**:检查虚拟机的网络设置,确保主机能够访问虚拟机的Redis服务。如果使用的是NAT模式,可能需要配置端口转发[^2]。
3. **Redis配置问题**:确认Redis是否允许远程连接。默认情况下,Redis只允许本地连接(`bind 127.0.0.1`)。需要修改Redis配置文件`redis.conf`中的`bind`参数为虚拟机的IP地址或`0.0.0.0`以允许所有IP访问[^1]。
4. **Spring Boot配置错误**:确保`application.properties`或`application.yml`中正确配置了Redis的连接信息,例如主机名、端口号和密码(如果设置了密码)[^3]。
以下是常见的Spring Boot Redis配置示例:
```properties
spring.redis.host=192.168.x.x # 虚拟机的IP地址
spring.redis.port=6379 # Redis默认端口
spring.redis.password=your_password # 如果设置了密码
spring.redis.timeout=5000ms # 连接超时时间
```
如果仍然无法连接,可以尝试以下步骤进行排查:
- **验证Redis服务状态**:在虚拟机上运行`redis-cli ping`命令,确认Redis服务是否正常响应。
- **检查防火墙设置**:确保虚拟机的防火墙没有阻止Redis端口(默认为6379)的访问[^3]。
- **测试连接性**:在主机上使用`telnet`或`nc`命令测试与虚拟机Redis端口的连通性。例如:
```bash
telnet 192.168.x.x 6379
```
如果上述步骤均无误,但问题仍未解决,可能是Lettuce连接池的配置问题。默认情况下,Spring Boot 2.x使用Lettuce作为Redis客户端。可以通过以下方式调整Lettuce的连接池配置:
```properties
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
```
此外,如果仍然遇到`UnknownHostException`,可能是DNS解析问题。可以尝试直接使用虚拟机的IP地址代替主机名[^4]。
### 示例代码:自定义RedisTemplate配置
如果默认配置无法满足需求,可以手动配置`RedisTemplate`以增强灵活性:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Bean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(stringRedisSerializer);
return template;
}
```
通过以上方法,通常可以有效解决Redis连接失败的问题。
---
阅读全文
相关推荐










