使用 SkyWalking 监控 Spring Cloud 微服务在 Docker 中的应用
随着微服务架构的普及,监控和性能管理显得尤为重要。Apache SkyWalking 是一个强大的应用性能管理(APM)工具,专为云原生架构和微服务设计。结合 Spring Cloud 和 Docker,我们可以方便地监控和管理多个微服务。本文将带你了解如何在 Docker 中使用 SkyWalking 来监控 Spring Cloud 应用,同时提供代码示例和旅行图。
1. 环境准备
在开始之前,请确保你已安装以下工具:
- Docker
- Docker Compose
- JDK 8 或以上
- Maven
2. 创建 Spring Cloud 微服务
接下来,我们将创建两个简单的 Spring Boot 微服务:service-a
和 service-b
。
2.1 创建 Service A
首先,创建一个新的 Spring Boot 项目 service-a
,并加入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-rest</artifactId>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-logging-logback</artifactId>
<version>8.x.x</version> <!-- 替换为最新版本 -->
</dependency>
</dependencies>
然后,在 ServiceAApplication
中设置基本的 REST 端点:
@RestController
@SpringBootApplication
public class ServiceAApplication {
@GetMapping(/api/service-a)
public String serviceA() {
return Hello from Service A;
}
public static void main(String[] args) {
SpringApplication.run(ServiceAApplication.class, args);
}
}
2.2 创建 Service B
同样,创建另一个 Spring Boot 应用service-b
,并添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-rest</artifactId>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-logging-logback</artifactId>
<version>8.x.x</version> <!-- 替换为最新版本 -->
</dependency>
</dependencies>
在 ServiceBApplication
中设置 REST 端点:
@RestController
@SpringBootApplication
public class ServiceBApplication {
@Autowired
private RestTemplate restTemplate;
@GetMapping(/api/service-b)
public String serviceB() {
String responseFromA = restTemplate.getForObject(http://service-a/api/service-a, String.class);
return Service B calls + responseFromA;
}
public static void main(String[] args) {
SpringApplication.run(ServiceBApplication.class, args);
}
}
2.3 Dockerfile
接下来,为每个服务编写Dockerfile
。
在 service-a
目录下创建 Dockerfile:
FROM openjdk:8-jdk-alpine
VOLUME /tmp
COPY target/service-a.jar app.jar
ENTRYPOINT [java,-jar,/app.jar]
在 service-b
目录下也创建相似的 Dockerfile。
2.4 Docker Compose 配置
然后,创建一个 docker-compose.yml
文件,用于同时运行 Spring Cloud 微服务和 SkyWalking。
version: '3'
services:
skywalking:
image: apache/skywalking-apm:8.x.x
ports:
- 8080:8080
service-a:
build: ./service-a
depends_on:
- skywalking
service-b:
build: ./service-b
depends_on:
- service-a
3. 旅行图
使用 Mermaid 来表示微服务之间的交互。以下是旅行图:
journey
title Microservice Interaction
section Service A Interaction
Service B calls Service A: 5: Service B
section Service B Interaction
Client calls Service B: 5: Client
4. 启动应用
现在,一切准备就绪。通过下面的命令启动 Docker 容器:
docker-compose up --build
你可以通过访问 http://localhost:8080
查看 SkyWalking 的监控界面。同时,通过访问 http://localhost:8081/api/service-b
可以触发 Service B,进而调用 Service A。
结论
通过将 Apache SkyWalking 与 Spring Cloud 微服务和 Docker 集成,我们能够高效地监控和管理微服务的性能。这种架构提供了很好的可扩展性和灵活性。希望本文能为你在微服务监控方面提供有用的帮助。随时欢迎探索 SkyWalking 的更多功能,提升应用的可观测性与性能管理能力。