Spring Cloud(十二):分佈式鏈路跟蹤 Sleuth 與 Zipkin【Finchley 版】

Spring Cloud(十二):分佈式鏈路跟蹤 Sleuth 與 Zipkin【Finchley 版】

隨着業務發展,系統拆分致使系統調用鏈路愈發複雜一個前端請求可能最終須要調用不少次後端服務才能完成,當整個請求變慢或不可用時,咱們是沒法得知該請求是由某個或某些後端服務引發的,這時就須要解決如何快讀定位服務故障點,以對症下藥。因而就有了分佈式系統調用跟蹤的誕生。html

現今業界分佈式服務跟蹤的理論基礎主要來自於 Google 的一篇論文《Dapper, a Large-Scale Distributed Systems Tracing Infrastructure》,使用最爲普遍的開源實現是 Twitter 的 Zipkin,爲了實現平臺無關、廠商無關的分佈式服務跟蹤,CNCF 發佈了布式服務跟蹤標準 Open Tracing。國內,淘寶的 「鷹眼」、京東的 「Hydra」、大衆點評的 「CAT」、新浪的 「Watchman」、惟品會的 「Microscope」、窩窩網的 「Tracing」 都是這樣的系統。前端

Spring Cloud Sleuth 也爲咱們提供了一套完整的解決方案。在本章中,咱們將詳細介紹如何使用 Spring Cloud Sleuth + Zipkin 來爲咱們的微服務架構增長分佈式服務跟蹤的能力。java

Spring Cloud Sleuth

通常的,一個分佈式服務跟蹤系統主要由三部分構成:react

  • 數據收集
  • 數據存儲
  • 數據展現

根據系統大小不一樣,每一部分的結構又有必定變化。譬如,對於大規模分佈式系統,數據存儲可分爲實時數據和全量數據兩部分,實時數據用於故障排查(Trouble Shooting),全量數據用於系統優化;數據收集除了支持平臺無關和開發語言無關係統的數據收集,還包括異步數據收集(須要跟蹤隊列中的消息,保證調用的連貫性),以及確保更小的侵入性;數據展現又涉及到數據挖掘和分析。雖然每一部分均可能變得很複雜,但基本原理都相似。git

服務追蹤的追蹤單元是從客戶發起請求(request)抵達被追蹤系統的邊界開始,到被追蹤系統向客戶返回響應(response)爲止的過程,稱爲一個 trace。每一個 trace 中會調用若干個服務,爲了記錄調用了哪些服務,以及每次調用的消耗時間等信息,在每次調用服務時,埋入一個調用記錄,稱爲一個 span。這樣,若干個有序的 span 就組成了一個 trace。在系統向外界提供服務的過程當中,會不斷地有請求和響應發生,也就會不斷生成 trace,把這些帶有 span 的 trace 記錄下來,就能夠描繪出一幅系統的服務拓撲圖。附帶上 span 中的響應時間,以及請求成功與否等信息,就能夠在發生問題的時候,找到異常的服務;根據歷史數據,還能夠從系統總體層面分析出哪裏性能差,定位性能優化的目標。github

Spring Cloud Sleuth 爲服務之間調用提供鏈路追蹤。經過 Sleuth 能夠很清楚的瞭解到一個服務請求通過了哪些服務,每一個服務處理花費了多長。從而讓咱們能夠很方便的理清各微服務間的調用關係。此外 Sleuth 能夠幫助咱們:web

  • 耗時分析: 經過 Sleuth 能夠很方便的瞭解到每一個採樣請求的耗時,從而分析出哪些服務調用比較耗時;
  • 可視化錯誤: 對於程序未捕捉的異常,能夠經過集成 Zipkin 服務界面上看到;
  • 鏈路優化: 對於調用比較頻繁的服務,能夠針對這些服務實施一些優化措施。

Spring Cloud Sleuth 能夠結合 Zipkin,將信息發送到 Zipkin,利用 Zipkin 的存儲來存儲信息,利用 Zipkin UI 來展現數據。算法

這是 Spring Cloud Sleuth 的概念圖:
spring

Zipkin

Zipkin 是 Twitter 的一個開源項目,它基於 Google Dapper 實現,它致力於收集服務的定時數據,以解決微服務架構中的延遲問題,包括數據的收集、存儲、查找和展示。
咱們可使用它來收集各個服務器上請求鏈路的跟蹤數據,並經過它提供的 REST API 接口來輔助咱們查詢跟蹤數據以實現對分佈式系統的監控程序,從而及時地發現系統中出現的延遲升高問題並找出系統性能瓶頸的根源。除了面向開發的 API 接口以外,它也提供了方便的 UI 組件來幫助咱們直觀的搜索跟蹤信息和分析請求鏈路明細,好比:能夠查詢某段時間內各用戶請求的處理時間等。
Zipkin 提供了可插拔數據存儲方式:In-Memory、MySql、Cassandra 以及 Elasticsearch。接下來的測試爲方便直接採用 In-Memory 方式進行存儲,生產推薦 Elasticsearch。docker

上圖展現了 Zipkin 的基礎架構,它主要由 4 個核心組件構成:

  • Collector:收集器組件,它主要用於處理從外部系統發送過來的跟蹤信息,將這些信息轉換爲 Zipkin 內部處理的 Span 格式,以支持後續的存儲、分析、展現等功能。
  • Storage:存儲組件,它主要對處理收集器接收到的跟蹤信息,默認會將這些信息存儲在內存中,咱們也能夠修改此存儲策略,經過使用其餘存儲組件將跟蹤信息存儲到數據庫中。
  • RESTful API:API 組件,它主要用來提供外部訪問接口。好比給客戶端展現跟蹤信息,或是外接系統訪問以實現監控等。
  • Web UI:UI 組件,基於 API 組件實現的上層應用。經過 UI 組件用戶能夠方便而有直觀地查詢和分析跟蹤信息。

快速上手

Zipkin 分爲兩端,一個是 Zipkin 服務端,一個是 Zipkin 客戶端,客戶端也就是微服務的應用。
客戶端會配置服務端的 URL 地址,一旦發生服務間的調用的時候,會被配置在微服務裏面的 Sleuth 的監聽器監聽,並生成相應的 Trace 和 Span 信息發送給服務端。
發送的方式主要有兩種,一種是 HTTP 報文的方式,還有一種是消息總線的方式如 RabbitMQ。

不論哪一種方式,咱們都須要:

  • 一個 Eureka 服務註冊中心,這裏咱們就用以前的eureka項目來當註冊中心。
  • 一個 Zipkin 服務端。
  • 兩個微服務應用,trace-atrace-b,其中trace-a中有一個 REST 接口/trace-a,調用該接口後將觸發對trace-b應用的調用。

方式一:HTTP

在 Spring Cloud Sleuth 中對 Zipkin 的整合進行了自動化配置的封裝,因此咱們能夠很輕鬆的引入和使用它。

Zipkin 服務端

關於 Zipkin 的服務端,在使用 Spring Boot 2.x 版本後,官方就不推薦自行定製編譯了,反而是直接提供了編譯好的 jar 包來給咱們使用,詳情請看 upgrade to Spring Boot 2.0 NoClassDefFoundError UndertowEmbeddedServletContainerFactory · Issue #1962 · openzipkin/zipkin · GitHub

而且之前的@EnableZipkinServer也已經被打上了@Deprecated

If you decide to make a custom server, you accept responsibility for troubleshooting your build or configuration problems, even if such problems are a reaction to a change made by the OpenZipkin maintainers. In other words, custom servers are possible, but not supported.

EnableZipkinServer.java github.com/openzipkin/zipkin/blob/master/zipkin-server/src/main/java/zipkin/server/EnableZipkinServer.java

 

簡而言之就是:私自改包,後果自負。

因此官方提供了一鍵腳本

1
2
curl -sSL https://zipkin.io/quickstart.sh | bash -s
java -jar zipkin.jar

 

若是用 Docker 的話,直接

1
docker run -d -p 9411:9411 openzipkin/zipkin

 

任一方式啓動後,訪問 http://localhost:9411/zipkin/ 就能看到以下界面,嗯還有漢化看起來不錯

至此服務端就 OK 了。

微服務應用

建立兩個基本的 Spring Boot 工程,名字分別爲trace-atrace-b

兩個工程的 pom.xml 均引入如下依賴座標

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

 

二者的配置文件也同樣(除了spring. application.nameserver.port,自行修改)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
spring:
application:
name: trace-a
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0 # 將採樣比例設置爲 1.0,也就是所有都須要。默認是 0.1
zipkin:
base-url: http://localhost:9411/ # 指定了 Zipkin 服務器的地址
server:
port: 8080
eureka:
client:
service-url:
defaultZone: http://localhost:7000/eureka/

 

Spring Cloud Sleuth 有一個 Sampler 策略,能夠經過這個實現類來控制採樣算法。採樣器不會阻礙 span 相關 id 的產生,可是會對導出以及附加事件標籤的相關操做形成影響。 Sleuth 默認採樣算法的實現是 Reservoir sampling,具體的實現類是 PercentageBasedSampler,默認的採樣比例爲: 0.1(即 10%)。不過咱們能夠經過spring.sleuth.sampler.percentage來設置,所設置的值介於 0.0 到 1.0 之間,1.0 則表示所有采集。

trace-a工程的啓動類以下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RestController
@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Autowired
private LoadBalancerExchangeFilterFunction lbFunction;

@Bean
public WebClient webClient() {
return WebClient.builder().baseUrl("http://trace-b")
.filter(lbFunction)
.build();
}

@GetMapping("/trace-a")
public Mono<String> trace() {
System.out.println("===call trace-a===");

return webClient().get()
.uri("/trace-b")
.retrieve()
.bodyToMono(String.class);
}

}

 

trace-b工程的啓動類以下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@GetMapping("/trace-b")
public Mono<String> trace() {
System.out.println("===call trace-b===");

return Mono.just("Trace");
}

}

 

至此,一切就緒。Spring 應用在監測到 classpath 中有 Sleuth 和 Zipkin 後,會自動在 WebClient(或 RestTemplate)的調用過程當中向 HTTP 請求注入追蹤信息,並向 Zipkin Server 發送這些信息。

進行驗證

咱們分別啓動 eureka、zipkin、trace-b、trace-a,而後
訪問 http://localhost:8080/trace-a 能夠獲得返回值Trace,同時還能在它們的控制檯中分別得到下面的輸出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- trace-a
===call trace-a===
2018-04-23 20:20:42.016 INFO [trace-a,,,] 71722 --- [ender@761e788f}] s.c.a.AnnotationConfigApplicationContext : Refreshing SpringClientFactory-localhost: startup date [Mon Apr 23 20:20:42 CST 2018]; parent: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext@41ab013
2018-04-23 20:20:42.103 INFO [trace-a,,,] 71722 --- [ender@761e788f}] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-04-23 20:20:42.421 INFO [trace-a,,,] 71722 --- [ender@761e788f}] c.netflix.config.ChainedDynamicProperty : Flipping property: localhost.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-04-23 20:20:42.441 INFO [trace-a,,,] 71722 --- [ender@761e788f}] c.n.u.concurrent.ShutdownEnabledTimer : Shutdown hook installed for: NFLoadBalancer-PingTimer-localhost
2018-04-23 20:20:42.476 INFO [trace-a,,,] 71722 --- [ender@761e788f}] c.netflix.loadbalancer.BaseLoadBalancer : Client: localhost instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=localhost,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2018-04-23 20:20:42.485 INFO [trace-a,,,] 71722 --- [ender@761e788f}] c.n.l.DynamicServerListLoadBalancer : Using serverListUpdater PollingServerListUpdater
2018-04-23 20:20:42.492 INFO [trace-a,,,] 71722 --- [ender@761e788f}] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client localhost initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=localhost,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@516a7895
2018-04-23 20:20:42.548 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] s.c.a.AnnotationConfigApplicationContext : Refreshing SpringClientFactory-trace-b: startup date [Mon Apr 23 20:20:42 CST 2018]; parent: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext@41ab013
2018-04-23 20:20:42.617 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-04-23 20:20:42.855 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty : Flipping property: trace-b.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-04-23 20:20:42.868 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] c.n.u.concurrent.ShutdownEnabledTimer : Shutdown hook installed for: NFLoadBalancer-PingTimer-trace-b
2018-04-23 20:20:42.869 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] c.netflix.loadbalancer.BaseLoadBalancer : Client: trace-b instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=trace-b,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2018-04-23 20:20:42.870 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer : Using serverListUpdater PollingServerListUpdater
2018-04-23 20:20:42.905 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty : Flipping property: trace-b.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-04-23 20:20:42.907 INFO [trace-a,d28b72b2317c023f,d28b72b2317c023f,true] 71722 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client trace-b initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=trace-b,current list of Servers=[172.16.106.93:8081],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
},Server stats: [[Server:172.16.106.93:8081; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@31f05c5
2018-04-23 20:20:43.878 INFO [trace-a,,,] 71722 --- [erListUpdater-1] c.netflix.config.ChainedDynamicProperty : Flipping property: trace-b.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647


-- trace-b
===call trace-b===
2018-04-23 20:20:43.944 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] s.c.a.AnnotationConfigApplicationContext : Refreshing SpringClientFactory-localhost: startup date [Mon Apr 23 20:20:43 CST 2018]; parent: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext@49c6c24f
2018-04-23 20:20:44.124 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-04-23 20:20:44.524 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] c.netflix.config.ChainedDynamicProperty : Flipping property: localhost.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-04-23 20:20:44.550 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] c.n.u.concurrent.ShutdownEnabledTimer : Shutdown hook installed for: NFLoadBalancer-PingTimer-localhost
2018-04-23 20:20:44.600 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] c.netflix.loadbalancer.BaseLoadBalancer : Client: localhost instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=localhost,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2018-04-23 20:20:44.610 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] c.n.l.DynamicServerListLoadBalancer : Using serverListUpdater PollingServerListUpdater
2018-04-23 20:20:44.617 INFO [trace-b,,,] 71662 --- [ender@22a10ac6}] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client localhost initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=localhost,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@1e1794d0

 

訪問 http://localhost:9411/zipkin
點擊 Find Traces 會看到有一條記錄

點擊記錄進去頁面,能夠看到每個服務所耗費的時間和順序

點擊依賴分析,能夠看到項目之間的調用關係

方式二:消息總線 RabbitMQ

由於以前說的 Zipkin 再也不推薦咱們來自定義 Server 端了,因此在最新版本的 Spring Cloud 依賴管理裏已經找不到 zipkin-server 了。
那麼若是直接用官方提供的 jar 包怎麼從 RabbitMQ 中獲取 trace 信息呢?

咱們能夠經過環境變量讓 Zipkin 從 RabbitMQ 中讀取信息,就像這樣:

1
RABBIT_ADDRESSES=localhost java -jar zipkin.jar

 

可配置的環境變量以下表所示:

屬性 環境變量 描述
zipkin.collector.rabbitmq.concurrency RABBIT_CONCURRENCY 併發消費者數量,默認爲1
zipkin.collector.rabbitmq.connection-timeout RABBIT_CONNECTION_TIMEOUT 創建鏈接時的超時時間,默認爲 60000毫秒,即 1 分鐘
zipkin.collector.rabbitmq.queue RABBIT_QUEUE 從中獲取 span 信息的隊列,默認爲 zipkin
zipkin.collector.rabbitmq.uri RABBIT_URI 符合 RabbitMQ URI 規範 的 URI,例如amqp://user:pass@host:10000/vhost

若是設置了 URI,則如下屬性將被忽略。

屬性 環境變量 描述
zipkin.collector.rabbitmq.addresses RABBIT_ADDRESSES 用逗號分隔的 RabbitMQ 地址列表,例如localhost:5672,localhost:5673
zipkin.collector.rabbitmq.password RABBIT_PASSWORD 鏈接到 RabbitMQ 時使用的密碼,默認爲 guest
zipkin.collector.rabbitmq.username RABBIT_USER 鏈接到 RabbitMQ 時使用的用戶名,默認爲guest
zipkin.collector.rabbitmq.virtual-host RABBIT_VIRTUAL_HOST 使用的 RabbitMQ virtual host,默認爲 /
zipkin.collector.rabbitmq.use-ssl RABBIT_USE_SSL 設置爲true則用 SSL 的方式與 RabbitMQ 創建連接

關於 Zipkin 的 Client 端,也就是微服務應用,咱們就在以前 trace-a、trace-b 的基礎上修改,只要在他們的依賴裏都引入spring-cloud-stream-binder-rabbit就行了,別的不用改。

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>

 

不過爲了說明是經過 RabbitMQ 傳輸的信息,我將spring.zipkin.base-url均改成http://localhost:9412/,即指向一個錯誤的地址。

分別重啓 trace-a、trace-b 工程,並啓動 Zipkin Server

1
RABBIT_ADDRESSES=localhost java -jar zipkin.jar

 

而後訪問 http://localhost:8080/trace-a 並刷新 Zipkin UI,看到以下內容,就說明 Sleuth+Zipkin+RabbitMQ 整合成功了。

此時看 RabbitMQ Admin,會看到多了一個名爲 zipkin 的 Queue

相關閱讀

Spring Cloud(一):服務治理技術概覽
Spring Cloud(二):服務註冊與發現 Eureka
Spring Cloud(三):服務提供與調用 Eureka
Spring Cloud(四):服務容錯保護 Hystrix
Spring Cloud(五):Hystrix 監控面板
Spring Cloud(六):Hystrix 監控數據聚合 Turbine
Spring Cloud(七):配置中心(Git 版與動態刷新)
Spring Cloud(八):配置中心(服務化與高可用)
Spring Cloud(九):配置中心(消息總線)
Spring Cloud(十):服務網關 Zuul(路由)
Spring Cloud(十一):服務網關 Zuul(過濾器)
Spring Cloud(十二):分佈式鏈路跟蹤(Sleuth 與 Zipkin)

示例代碼:GitHub

 

相關文章
相關標籤/搜索