在现代微服务架构中,分布式系统追踪是一个关键需求。Jaeger 是一个开源的分布式追踪系统,能够帮助开发者监控和分析分布式系统的性能与行为。本文将介绍如何在Java项目中集成Jaeger,并通过代码示例展示其实际应用。
Jaeger 是由 Uber 开源的一个分布式追踪工具,支持 OpenTracing 标准。它可以帮助开发人员监控和优化分布式系统的性能,提供以下功能:
在开始之前,请确保已安装以下内容:
docker run -d --name jaeger \
-e COLLECTOR_ZIPKIN_HTTP_PORT=9411 \
-p 5775:5775/udp \
-p 6831:6831/udp \
-p 6832:6832/udp \
-p 5778:5778 \
-p 16686:16686 \
-p 14268:14268 \
-p 14250:14250 \
-p 9411:9411 \
jaegertracing/all-in-one:latest
访问 http://localhost:16686
可以查看 Jaeger UI。
在项目的 pom.xml
文件中添加以下依赖项:
<dependency>
<groupId>io.opentracing.contrib</groupId>
<artifactId>opentracing-spring-jaeger-cloud-starter</artifactId>
<version>3.4.0</version>
</dependency>
在 application.properties
中添加以下配置:
# Jaeger configuration
spring.sleuth.sampler.probability=1.0
spring.jaeger.udp-sender.host=localhost
spring.jaeger.udp-sender.port=6831
spring.jaeger.service-name=my-service
spring.sleuth.sampler.probability=1.0
表示采样率为100%。spring.jaeger.service-name
定义了服务名称。创建一个简单的 Spring Boot 项目,包含两个服务:ServiceA
和 ServiceB
。ServiceA
调用 ServiceB
,并记录整个调用链路。
package com.example.servicea;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ServiceAApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceAApplication.class, args);
}
}
@RestController
class ServiceARestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/call-b")
public String callServiceB() {
return restTemplate.getForObject("http://localhost:8081/service-b", String.class);
}
}
package com.example.serviceb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class ServiceBApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceBApplication.class, args);
}
}
@RestController
class ServiceBRestController {
@GetMapping("/service-b")
public String serviceB() {
return "Response from Service B";
}
}
分别启动 ServiceA
和 ServiceB
,并在浏览器中访问 http://localhost:8080/call-b
。此时,Jaeger 将会记录整个调用链路。
打开 http://localhost:16686
,选择服务名称 my-service
,即可看到完整的调用链路。
spring.sleuth.sampler.probability
),可以减少追踪数据对生产环境的影响。