前言
分布式環境下,服務直接相互調用,一個復雜的業務可能要調用多個服務,例如A -> B -> C -> D,如何追蹤http請求的軌跡?
本文記錄Spring Cloud Sleuth + Zipkin實現分布式鏈路追蹤
代碼編寫
zipkin-server
一個普通SpringBoot項目,繼承我們的SpringCloud工程的父類pom,引入zipkin服務依賴,為了方便管理,也將它作為客戶端注冊到eureka
pom文件
<dependencies> <!-- eureka-client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- zipkin --> <!-- 從 2.12.6 版本開始有個較大的更新,遷移使用 Armeria HTTP 引擎。從此版本開始,若直接添加依賴的 Spring Boot 應用啟動會存在沖突 2.12.5,會使用默認8080 --> <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-server</artifactId> <version>2.12.3</version> <!-- 引入zipkin-server包時idea報錯Exception in thread "main" java.lang.StackOverflowError --> <exclusions> <exclusion> <artifactId>log4j-slf4j-impl</artifactId> <groupId>org.apache.logging.log4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.zipkin.java</groupId> <artifactId>zipkin-autoconfigure-ui</artifactId> <version>2.12.3</version> </dependency> </dependencies>
配置文件
server.port=10000 spring.application.name=zipkin-server management.metrics.web.server.auto-time-requests=false #logging.level.root=debug eureka.client.serviceUrl.defaultZone=http://127.0.0.1:1111/eureka/ #健康檢查(需要spring-boot-starter-actuator依賴) eureka.client.healthcheck.enabled=true # 續約更新時間間隔(默認30秒) eureka.instance.lease-renewal-interval-in-seconds=10 # 續約到期時間(默認90秒) eureka.instance.lease-expiration-duration-in-seconds=10 #eureka服務列表顯示ip+端口 eureka.instance.prefer-ip-address=true eureka.instance.instance-id=http://${spring.cloud.client.ip-address}:${server.port} eureka.instance.hostname= ${spring.cloud.client.ip-address}
啟動類
@EnableZipkinServer @EnableEurekaClient @SpringBootApplication public class ZipkinServerApplication { public static void main(String[] args) { SpringApplication.run(ZipkinServerApplication.class, args); } }
zipkin-client
每個業務模塊都應屬於客戶端,在我們的demo例子中,service-a、service-b1/service-b2、service-c模塊pom都引入
<!-- 分布式鏈路追蹤 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zipkin</artifactId> </dependency>
新增配置文件zipkin.properties
spring.zipkin.base-url=http://127.0.0.1:10000 spring.sleuth.sampler.probability=1.0
然后在自定義MyEnvironmentPostProcessor中,將配置文件加載到Environment環境中
這樣便完成一個zipkin-client的配置
效果演示
不必啟動所以服務,將測試涉及到的服務啟動即可(記得啟動redis、mysql服務)
通過zuul網關調用service-a的ribbon接口,進行測試
訪問zipkin-server服務:http://localhost:10000,跳轉可視化頁面,點擊查詢查看追蹤日志
如果我們關閉service-b服務
還可以查看請求中的服務依賴關系
后記
分布式鏈路追蹤暫時先記錄到這,后續再進行補充
代碼開源
代碼已經開源、托管到我的GitHub、碼雲:
GitHub:https://github.com/huanzi-qch/springCloud
碼雲:https://gitee.com/huanzi-qch/springCloud