Spring Boot和Redis容器之间的通信

我使用基于Spring Boot框架的REST API实现了简单的独立Web应用程序。 我的应用程序使用Redis来caching一些数据。 现在我想dockerize webapp和Rediscaching提供简单的运行程序,而不会在工作环境中强制Redis安装。

我尝试了很多方法,但我仍然努力与RedisConnectionFailureException: Cannot get Jedis connection和根本原因ConnectException: Connection refused

pom.xml中:

 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>com.spotify</groupId> <artifactId>dockerfile-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <repository>${project.artifactId}</repository> </configuration> </plugin> </plugins> </build> 

泊坞窗,compose.yml:

 version: '3' services: web: build: . ports: - "8080:8080" links: - redis redis: image: redis ports: - "6379:6379" 

Dockerfile:

 FROM openjdk:8-jdk-alpine VOLUME /tmp ADD target/xxx.jar abc.jar ENV JAVA_OPTS="" ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS - Djava.security.egd=file:/dev/./urandom -jar /abc.jar" ] 

application.properties:

 spring.redis.host=redis spring.redis.port=6379 

我通过构造函数自动ValueOperations StringRedisTemplate ,从模板中获取ValueOperations ,并简单地使用它(没有额外的Redisconfiguration)。 我运行应用程序与命令sudo docker-compose up和上面列出的每个Sprin启动应用程序调用Redis的exception。 Rediscaching可以从主机访问。 没有Docker和安装Redis服务的时候,一切正常。

更新:我正在使用我以前粘贴的application.properties和application.yml我存储一些自定义configuration有关我的应用程序(不是框架configuration)的逻辑。 我读过这不应该是一个问题,因为Spring Boot加载这两个文件并合并它们。 我怀疑Redis主机没有在Jedis连接上正确设置,但我不知道如何检查它。

尝试创build一个dockernetworking并将容器附加到这个networking:

docker network create spring

 version: '3' services: web: build: . ports: - "8080:8080" networks: - spring redis: image: redis command: [ "redis-server", "--protected-mode", "no" ] ports: - "6379:6379" networks: - spring networks: spring: external: true 

最后我意识到了这个问题。 我使用sudo docker-compose up命令启动应用程序,如上所述。 此命令重新运行以前启动的容器(不会每次重build图像),所以我提供的所有更改都没有考虑在内。 我认为项目代码将被重新编译。

以上configuration对我来说工作很好。 只需运行sudo docker-compose down && mvn clean install然后sudo docker-compose up