【发布时间】:2016-09-03 07:00:00
【问题描述】:
我有一个 Spring Boot 应用程序,它连接到一个用作缓存的 Redis 实例。当我在开发环境中时,我有以下内容:
---
spring:
profiles: default
redis:
host: localhost
port: 6379
而我的缓存配置类是这样的:
@Configuration
@EnableCaching
public class CacheConfiguration {
@Value("${redis.host}")
String redisHost;
@Value("${redis.port}")
int redisPort;
在生产中,这个应用程序是 Dockerized,我有以下 docker-compose.yml 文件:
redis:
image: tutum/redis
ports:
- "6379:6379"
volumes:
- /data
app:
build: .
ports:
- "8080:8080"
links:
- redis
application.yml 是:
---
spring:
profiles: docker
redis:
host: redis
port: 6379
为了在 Docker 上启动应用程序,我使用-Dspring.profiles.active=docker 运行,但是当应用程序启动时,出现以下错误:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private int com.inkdrop.config.cache.CacheConfiguration.redisPort; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [int]; nested exception is java.lang.NumberFormatException: For input string: "tcp://172.17.0.3:6379"
出于某种原因,Spring Boot 将redis.port 读取为tcp://172.17.0.3:6379。因此,对于测试建议,我从CacheConfiguration 类中删除了@Value 注释,并手动将其设置为redis 作为主机和6379 作为端口并且它工作。好像在使用环境变量和@Value 时,Spring 迷路了。有人有想法吗?
【问题讨论】:
-
您使用的是哪个 Spring Boot 版本?另外我会尝试在 docker compose 文件本身中设置环境变量:
environment: redis.port=6379,看看会发生什么。 -
现在使用 1.3.4。我试试看
标签: java spring docker spring-boot docker-compose