基于Spring Cloud Alibaba+Skywalking的分布式链路追踪设计
以下是一个简化的Spring Cloud Alibaba和SkyWalking结合使用的示例代码。
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Cloud Alibaba dependencies -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<!-- SkyWalking dependencies -->
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-trace</artifactId>
</dependency>
</dependencies>
- 在
application.yml
中配置SkyWalking和服务发现:
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
sentinel:
transport:
dashboard: 127.0.0.1:8080
port: 8719
skywalking:
discovery:
service-instance-name: ${spring.application.name}:${spring.application.instance_id:${server.port}}
service-name: ${spring.application.name}
management:
endpoints:
web:
exposure:
include: '*'
- 在启动类上添加@EnableSkyWalking注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.annotation.EnableTrace;
@EnableSkyWalking
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 创建一个服务并使用SkyWalking的追踪注解:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.annotation.TraceCrossThread;
@RestController
public class MyController {
@GetMapping("/hello")
@Trace(operationName = "helloService")
public String hello() {
// 模拟跨线程调用
Runnable task = () -> {
// 使用跨线程追踪
TracedRunnable.run(new Runnable() {
@Override
public void run() {
System.out.
评论已关闭