本文源碼:GitHub·點這裡 || GitEE·點這裡
一、鍊路追蹤簡介
1、Sleuth元件簡介
Sleuth是SpringCloud微服務系統中的一個元件,實作了鍊路追蹤解決方案。可以定位一個請求到底請求了哪些具體的服務。在複雜的微服務系統中,如果請求發生了異常,可以快速捕獲問題所在的服務。
2、項目結構
- 啟動順序如下
* 注冊中心
node07-eureka-7001
* 鍊路資料收集服務
node07-zipkin-7003
* 服務提供
node07-provider-6001
node07-provider-6002
* 網關路由
node07-zuul-7002
二、搭建鍊路服務
1、核心依賴
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
- 啟動類注解:@EnableZipkinServer
2、配置檔案
server:
port: 7003
spring:
application:
name: node07-zipkin-7003
eureka:
instance:
hostname: zipkin-7003
prefer-ip-address: true
client:
service-url:
defaultZone: http://registry01.com:7001/eureka/
三、服務配置
這裡網關,zuul-7002,服務提供,provider-6001,provider-6002的配置相同。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
spring:
zipkin:
base-url: http://localhost:7003
sleuth:
sampler:
# 資料 100% 上傳
percentage: 1.0
四、測試流程
1、注冊中心
一次啟動上述服務之後,檢視注冊中心:

2、請求流程
通路接口
http://localhost:7002/v1/api-6001/get6001Info
這個請求從網關服務進入,到達6001端口服務之後,請求6002端,最終傳回結果。
- 6001接口
@Autowired
private RestTemplate restTemplate ;
@RequestMapping("/get6001Info")
public String get6001Info (){
String server_name = "http://node07-provider-6002" ;
return restTemplate.getForObject(server_name+"/get6002Info",String.class) ;
}
- 6002接口
@RequestMapping(value = "/get6002Info",method = RequestMethod.GET)
public String get6002Info () {
LOG.info("provider-6002");
return "6002Info" ;
}
3、鍊路管理界面
1)、UI界面
http://localhost:7003/zipkin/
2)、依賴分析
如圖點選,【依賴分析】,和上面描述的請求過程完全一緻。
五、源代碼位址
GitHub·位址
https://github.com/cicadasmile/spring-cloud-base
GitEE·位址
https://gitee.com/cicadasmile/spring-cloud-base