微服務架構上經過業務來劃分服務的,經過REST調用,對外暴露的一個接口,可能須要不少個服務協同才能完成這個接口功能,若是鏈路上任何一個服務出現問題或者網絡超時,都會造成致使接口調用失敗。隨着業務的不斷擴張,服務之間互相調用會愈來愈複雜,在項目中引入sleuth能夠方便程序進行調試。java
Spring Cloud Sleuth爲服務之間調用提供鏈路追蹤。經過Sleuth能夠很清楚的瞭解到一個服務請求通過了哪些服務,每一個服務處理花費了多長。從而讓咱們能夠很方便的理清各微服務間的調用關係。此外Sleuth能夠幫助咱們:算法
改造前面的feign、service(服務)spring
pom增長:瀏覽器
<!--sleuth跟蹤--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency>
@Autowired
private IFeignService feignService; private static Logger log = LoggerFactory.getLogger(FeignController.class); @RequestMapping("/index") public String index(){ log.info("feign info"); return feignService.index(); // @FeignClient(value = "service-hello")
}
private static Logger log = LoggerFactory.getLogger(HelloController.class);
@RequestMapping("/index")
public String index() {
log.info("service info");
System.err.println("服務提供者client:" + name + "服務端口:" + port);
return "服務提供者client:" + name + "服務端口:" + port;
}
打開頁面,正常springboot
顯示的日誌以下:服務器
2018-12-29 16:24:26.048 INFO [service-feign,1d270312e94cab85,1d270312e94cab85,false] 10692 --- [nio-8886-exec-8] c.e.fegin.controller.FeignController : feign info 2018-12-29 16:24:26.056 INFO [service-hello,1d270312e94cab85,5e23c30b75ee6755,false] 6560 --- [nio-8883-exec-5] c.e.e.controller.HelloController : service info
[appname,traceId,spanId,exportable]
,也就是Sleuth的跟蹤數據。其中:
Zipkin是一個致力於收集分佈式服務的時間數據的分佈式跟蹤系統。其主要涉及如下四個組件:網絡
Zipkin提供了可插拔數據存儲方式:In-Memory、MySql、Cassandra以及Elasticsearch。接下來的測試爲方便直接採用In-Memory方式進行存儲,我的推薦Elasticsearch,特別是後續當咱們須要整合ELK時。架構
用的springboot2,因此構建zipkin沒有找到適合的方法(@EnableZipkinServer....失效),因此直接在官網https://zipkin.io/下載了jar包運行:app
打開http://localhost:9411分佈式
修改feign、service:
<!--sleuth跟蹤--> <!--<dependency>--> <!--<groupId>org.springframework.cloud</groupId>--> <!--<artifactId>spring-cloud-starter-sleuth</artifactId>--> <!--</dependency>--> <!-- Zipkin 已包含spring-cloud-starter-sleuth --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zipkin</artifactId> </dependency>
properties配置:
spring.zipkin.base-url=http://localhost:9411
spring.sleuth.sampler.percentage=1.0 # 默認
咱們在瀏覽器中訪問幾回服務http://localhost:8886/index,而後轉到Zipkin服務器
該界面對本次請求進行了更詳細的展示。一樣咱們還能夠再點擊,以查看更爲詳細的數據,能夠看到以下界面
在Zipkin界面中咱們還能夠查看各服務之間的依賴關係
Zipkin能夠在跟蹤記錄中顯示錯誤信息。當異常拋出而且沒有捕獲,Zipkin就會自動的換個顏色顯示。在跟蹤記錄的清單中,當看到紅色的記錄時,就表示有異常拋出了。
關掉service-hello
點擊進去以獲取更詳細的錯誤信息。
在生成環境中,因爲業務量比較大,所產生的跟蹤數據可能會很是大,若是所有采集一是對業務有必定影響,二是對存儲壓力也會比較大,因此採樣變的很重要。通常來講,咱們也不須要把每個發生的動做都進行記錄。
Spring Cloud Sleuth有一個Sampler策略,能夠經過這個實現類來控制採樣算法。採樣器不會阻礙span相關id的產生,可是會對導出以及附加事件標籤的相關操做形成影響。 Sleuth默認採樣算法的實現是Reservoir sampling,具體的實現類是PercentageBasedSampler
,默認的採樣比例爲: 0.1
(即10%)。
咱們能夠經過spring.sleuth.sampler.percentage
來設置,所設置的值介於0.0到1.0之間,1.0則表示所有采集。
也能夠經過實現bean的方式來設置採樣爲所有采樣(AlwaysSampler)或者不採樣(NeverSampler)