所以我目前有一个eccomerce项目的服务,它使用redis和jedis来连接。使用源代码运行时它可以工作,但是当它被docker化时,它会弹出以下错误:
redis.clients.jedis.exceptions.JedisConnectionException: Failed to connect to any host resolved for DNS name.
当我运行 redis docker 容器和我的服务的源代码时,它工作没有问题
Docker 撰写:
version: '3'
services:
order-api:
build:
context: ./orderapi
dockerfile: Dockerfile
ports:
- "8002:8002"
depends_on:
- redis
environment:
- MYSQL_HOST=host.docker.internal
- MYSQL_PORT=3306
- MYSQL_DATABASE=ecommerce_fyp_order
- MYSQL_USER=root
- MYSQL_PASSWORD=12345
- REDIS_HOST=redis #options: host.docker.internal, redis, localhost
- REDIS_PORT=6379
networks:
- net
redis:
image: redis:latest #IPaddress is 172.18.0.2
ports:
- "6379:6379"
command: ["redis-server", "--bind", "redis", "--port", "6379"]
networks:
- net
networks:
net:
driver: bridge
我在 Spring Boot 中对此进行编码,以下是我的服务的 application.properties:
server.port=8002
spring.application.name=orderapi
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/ecommerce_fyp_order
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql: true
#Redis
spring.session.redis.namespace=session
spring.data.redis.host=localhost
spring.data.redis.port=6379
Redis 配置:
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
我尝试将 REDIS_HOST 更改为 redis、host.docker.internal、redis、localhost,但都不起作用。
非常感谢任何帮助解决此问题的帮助。
更新:我尝试使用 docker 命令连接到 redis 容器
docker exec -it e-commercenew-redis-1 redis-cli
我收到以下错误
Could not connect to Redis at 127.0.0.1:6379: Connection refused
当我运行 redis 容器并使用 spring boot 源代码运行服务时它可以工作,但是当使用 docker compose 运行时它不起作用,所以不太确定为什么连接被拒绝
有关如何在 docker 上解决此问题的任何建议,谢谢
读取你的docker文件,它表明你构建了一个内部网络并通过其名称请求服务。但是,您在 Spring 应用程序 yaml 文件中使用硬代码定义了 Redis 主机?你没有意识到配置
spring.data.redis.host=localhost
很奇怪吗?
为了解决这个问题,你应该定义
spring.data.redis.host={REDIS_HOST:localhost}
,它会从部署环境中读取变量,即您在当前场景中的 docker compose 文件中指定的 redis 主机,如果为空,则采用默认值 localhost 。
- REDIS_HOST=redis #options: host.docker.internal, redis, localhost