docker-compose實現(xiàn)訪問計數(shù)javaweb服務(wù)

需求
利用 docker compose 快速搭建一個可以統(tǒng)計訪問次數(shù)的 java web服務(wù).
環(huán)境準備
安裝 docker.
- docker
- docker desktop (window | mac)
步驟
1 新建 java web 服務(wù)
spring boot 2.x
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.11</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <java.version>8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </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> </plugins> </build>
編寫 Controller .
@RestController public class AccessCounterController { @Autowired private StringRedisTemplate stringRedisTemplate; @GetMapping("/hello") public String hello() { Long counter = stringRedisTemplate.opsForValue().increment("accCounter"); return "頁面訪問的次數(shù): " + counter; } }
項目配置
server.port=8080 spring.redis.host=redis spring.redis.port=6379
2 Dockerfile 和 docker-compose.yml
FROM java:8 COPY target/*.jar /app/acc-counter/app.jar CMD ["--server.port=8080"] WORKDIR /app/acc-counter EXPOSE 8080 ENTRYPOINT ["java", "-jar", "app.jar"] version: "3.9" services: acc-counter-app: build: . image: acc-counter-app depends_on: - redis ports: - "8080:8080" redis: image: "library/redis:alpine"
3 打包工程
mvn package
4 up
docker-compose up -d
第一次會自動先 build.
訪問一下
坑
- 如果后續(xù)需要修改 Dockerfile 配置, 修改后, 要先顯示
docker-compose build
, 否則, 即使你使用up
指令新的修改不生效, 因為它會識別到之前build的過, 不會重新build. - 注意環(huán)境版本, 我這里使用 java8+springboot 2.x+maven 3.x
標簽: