使用 Spring Cloud Sleuth 和 Stackdriver Trace 進行分散式追蹤

使用 Spring Cloud Sleuth 和 Stackdriver Trace 進行分散式追蹤

程式碼研究室簡介

subject上次更新時間:2月 10, 2020
account_circle作者:Google 員工

1. 總覽

分散式追蹤對於取得多層微服務架構的深入分析資訊和觀測能力相當重要。從服務 A 到服務 B 到服務 C 進行服務呼叫呼叫時,請務必瞭解呼叫成功和每個步驟的延遲時間。

在 Spring Boot 中,您可以使用 Spring Cloud Sleuth 將分散式追蹤檢測功能順暢地新增至您的應用程式。根據預設,可將追蹤資料轉送至 Zipkin。

Google Cloud Platform 的 Stackdriver Trace 是一項代管服務,可讓您儲存追蹤資料,而且不必管理自己的 Zipkin 執行個體和儲存空間。Stackdriver Trace 也可以產生延遲時間分佈報表,並自動偵測效能迴歸。

您可以透過下列兩種方式使用 Spring Boot 應用程式,使用 Stackdriver Trace:

  1. 使用 Stackdriver Trace Zipkin Proxy,只要設定 Spring Cloud Sleuth 即可將此 Proxy 設定為 Zipkin 端點
  2. 或者,您也可以使用 Spring Cloud GCP Trace 與 Spring Cloud Sleuth 完美整合,並將追蹤記錄資料直接轉送至 Stackdriver Trace。

在本程式碼研究室中,您將瞭解如何建構新的 Spring Boot 應用程式,以及如何使用 Spring Cloud GCP Trace 進行分散式追蹤。

您將會瞭解的內容

  • 如何建立 Spring Boot Java 應用程式及設定 Stackdriver Trace。

軟硬體需求

  • Google Cloud Platform 專案
  • 瀏覽器,例如 ChromeFirefox
  • 熟悉標準 Linux 文字編輯器,例如 Vim、EMAC 或 Nano

您要如何使用本教學課程?

您對於建立 HTML/CSS 網路應用程式體驗有什麼評價?

您對於 Google Cloud Platform 服務的使用體驗評價如何?

2. 設定和需求

自行調整環境設定

如果您還沒有 Google 帳戶 (Gmail 或 Google Apps),請先建立帳戶。登入 Google Cloud Platform 主控台 (console.cloud.google.com),然後建立新專案:

2016-02-10 12:45:26.png 的螢幕擷取畫面

提醒您,專案編號是所有 Google Cloud 專案的不重複名稱 (使用上述名稱後就無法使用,敬請見諒!)此程式碼研究室稍後將稱為 PROJECT_ID

接著,您必須在 Cloud Console 中啟用計費功能,才能使用 Google Cloud 資源。

完成這個程式碼研究室的成本應該不會超過新臺幣 $300 元,但如果您決定繼續使用更多資源,或是讓資源繼續運作 (請參閱本文件結尾的「清除設定」一節),就有可能需要更多成本。

新加入 Google Cloud Platform 的使用者可免費試用$300 美元

Google Cloud Shell

雖然 Google Cloud 和 Kubernetes 可透過筆記型電腦從遠端執行,但在這個程式碼研究室中,我們會使用 Google Cloud Shell,這是一個在 Cloud 中執行的指令列環境。

啟用 Google Cloud Shell

在 GCP 主控台中,按一下右上角的工具列的 Cloud Shell 圖示:

然後按一下 [Start Cloud Shell]。

佈建和連線至環境只需要幾分鐘的時間:

這部虛擬機器已載入所有您需要的開發工具。這項服務提供永久性的 5GB 主目錄,可在 Google Cloud 中運作,大幅提升網路效能和驗證效能。在這個研究室中,您可以透過瀏覽器或 Google Chromebook 完成大部分的工作。

連線至 Cloud Shell 之後,您應該會看到您已經通過驗證,且專案已經設定為 PROJECT_ID

在 Cloud Shell 中執行下列指令,確認您的身分已通過驗證:

gcloud auth list

指令輸出

Credentialed accounts:
 - <myaccount>@<mydomain>.com (active)
gcloud config list project

指令輸出

[core]
project = <PROJECT_ID>

如果沒有,則可使用下列指令設定:

gcloud config set project <PROJECT_ID>

指令輸出

Updated property [core/project].

3. 建立新的 Spring Boot REST 服務

Cloud Shell 啟動後,您可以使用指令列使用 Spring Initializr 產生新的 Spring Boot 應用程式:

$ curl https://start.spring.io/starter.tgz -d packaging=jar \
 
-d dependencies=web,lombok,cloud-gcp,cloud-starter-sleuth \
 
-d baseDir=trace-service-one | tar -xzvf - \
 
&& cd trace-service-one

透過新增類別來建立新的 REST 控制器:

src/main/java/com/example/demo/WorkController.java

package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@Slf4j
public class WorkController {
 
Random r = new Random();

 
public void meeting() {
   
try {
      log
.info("meeting...");
     
// Delay for random number of milliseconds.
     
Thread.sleep(r.nextInt(500));
   
} catch (InterruptedException e) {
   
}
 
}

 
@GetMapping("/")
 
public String work() {
   
// What is work? Meetings!
   
// When you hit this URL, it'll call meetings() 5 times.
   
// Each time will have a random delay.
    log
.info("starting to work");
   
for (int i = 0; i < 5; i++) {
     
this.meeting();
   
}
    log
.info("finished!");
   
return "finished work!";
 
}
}

您可以使用 Spring Boot 外掛程式正常啟動 Spring Boot 應用程式。我們來略過這項研究室的測試:

$ ./mvnw -DskipTests spring-boot:run

應用程式啟動後,按一下 Cloud Shell 工具列中的 [Web Preview] 圖示 ,然後選擇 [透過通訊埠 8080 預覽]

稍候片刻,您應該會看到結果:

您可能也會在 Cloud Shell 中看到含有追蹤 ID 與時距 ID 的記錄訊息:

4. 使用 Stackdriver Trace

啟用 Stackdriver Trace API

您必須先啟用 Stackdriver Trace API,才能使用 Stackdriver Trace 儲存追蹤記錄資料。如要啟用 API,請前往 [API 服務] → [程式庫]

搜尋 Stackdriver Trace

點選 [Stackdriver Trace API],然後按一下 [啟用] (如果尚未啟用)。

設定應用程式預設憑證

在這個研究室中,您必須設定應用程式預設憑證。此憑證將由 Spring Cloud GCP Trace 入門程序自動擷取。

首先,請登入帳戶:

$ gcloud auth application-default login
You are running on a Google Compute Engine virtual machine.
The service credentials associated with this virtual machine
will automatically be used
by Application Default
Credentials, so it is not necessary to use this command.
If you decide to proceed anyway, your user credentials may be visible
to others
with access to this virtual machine. Are you sure you want
to authenticate
with your personal account?
Do you want to continue (Y/n)? Y

Go to the following link in your browser:
    https
://accounts.google.com/o/oauth2/auth...
Enter verification code: ...

點選連結開啟新的瀏覽器分頁,然後按一下 [允許]

接著,將驗證碼複製並貼到 Cloud Shell 中,然後按下 Enter 鍵。您應該會看到:

Credentials saved to file: [/tmp/tmp.jm9bnQ4R9Q/application_default_credentials.json]
These credentials will be used by any library that requests
Application Default Credentials.

新增 Spring Cloud GCP Trace

在這項服務中,我們使用「春季 Cloud Sleuth」進行追蹤。由此新增 Spring Cloud GCP Trace 入門工具,以便將資料轉送至 Stackdriver Trace。

新增 Spring Cloud GCP Trace 依附元件:

pom.xml

<project>
  ...
 
<dependencies>
    ...
   
<!-- Add Stackdriver Trace Starter -->
   
<dependency>
     
<groupId>org.springframework.cloud</groupId>
     
<artifactId>spring-cloud-gcp-starter-trace</artifactId>
   
</dependency>
 
</dependencies>
  ...
</project>

根據預設,Spring Cloud Sleuth 不會對每個要求進行取樣。為了簡化測試程序,請將 application.properties 的取樣率提高到 100%,確保我們能查看追蹤記錄資料,並忽略一些我們不在乎的部分網址:

$ echo "
spring.sleuth.sampler.probability=1.0
spring.sleuth.web.skipPattern=(^cleanup.*|.+favicon.*)
"
> src/main/resources/application.properties

再次執行應用程式,然後使用 Cloud Shell Web Preview 查看應用程式:

$ export GOOGLE_CLOUD_PROJECT=`gcloud config list --format 'value(core.project)'`
$
./mvnw -DskipTests spring-boot:run

根據預設,Spring Cloud GCP Trace 會批次處理追蹤記錄,並將資料每 10 秒傳送一次,或是收到最低數量的追蹤記錄資料。您可以設定這個架構,詳情請參閱 Spring Cloud GCP Trace 參考說明文件

向服務提出要求:

$ curl localhost:8080

在 Cloud Console 中,瀏覽至 [Stackdriver] → [追蹤記錄] → [追蹤記錄清單]

將時間範圍縮小到 1 小時。「自動重新載入」功能預設為開啟。因此,當追蹤資料送達時,應該就會顯示在控制台中!

追蹤記錄資料將在 30 秒左右左右顯示。

按一下藍色圓點,即可查看追蹤記錄詳細資料:

很簡單吧!

5. 建立第二個 Spring Boot 網路應用程式

按一下「+」圖示來開啟新的 Cloud Shell 工作階段:

在新工作階段中,建立第二個 Spring Boot 應用程式:

$ curl https://start.spring.io/starter.tgz -d packaging=jar \
 
-d dependencies=web,lombok,cloud-gcp,cloud-starter-sleuth \
 
-d baseDir=trace-service-two | tar -xzvf - \
 
&& cd trace-service-two

透過新增類別來建立新的 REST 控制器:

src/main/java/com/example/demo/MeetingController.java

package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@Slf4j
public class MeetingController {
 
Random r = new Random();

 
@GetMapping("/meet")
 
public String meeting() {
   
try {
      log
.info("meeting...");
     
Thread.sleep(r.nextInt(500 - 20 + 1) + 20);
   
} catch (InterruptedException e) {
   
}
   
return "finished meeting";
 
}
}

將 Spring Cloud GCP Trace 新增至 pom.xml

pom.xml

<project>
  ...
 
<dependencies>
    ...
   
<!-- Add Stackdriver Trace starter -->
   
<dependency>
     
<groupId>org.springframework.cloud</groupId>
     
<artifactId>spring-cloud-gcp-starter-trace</artifactId>
   
</dependency>
 
</dependencies>
  ...
</project>

設定 Sleuth 取樣 100% 的要求:

src/main/resources/application.properties

$ echo "
spring.sleuth.sampler.probability=1.0
spring.sleuth.web.skipPattern=(^cleanup.*|.+favicon.*)
"
> src/main/resources/application.properties

最後,您可以使用 Spring Boot 外掛程式在通訊埠 8081 啟動 Spring Boot 應用程式:

$ export GOOGLE_CLOUD_PROJECT=`gcloud config list --format 'value(core.project)'`
$
./mvnw -DskipTests spring-boot:run -Dserver.port=8081

6. 將第一個服務更新為採用第二項服務

trace-service-two 執行期間,請返回第一個 Cloud Shell 工作階段視窗並修改為 trace-service-one

首先初始化新的 RestTemplate 豆:

src/main/java/com/example/demo/DemoApplication.java

package com.example.demo;

...

import org.springframework.web.client.RestTemplate;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class DemoApplication {
       
@Bean
       
public RestTemplate restTemplate() {
               
return new RestTemplate();
       
}
       
       
public static void main(String[] args) {
               
SpringApplication.run(DemoApplication.class, args);
       
}
}

WorkController.meeting() 中透過 Meet 服務撥打電話。

src/main/java/com/example/demo/WorkController.java

package com.example.demo;

...
import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Autowired;

@RestController
@Slf4j
public class WorkController {
 
@Autowired
 
RestTemplate restTemplate;

 
public void meeting() {
   
String result = restTemplate.getForObject("http://localhost:8081/meet", String.class);
    log
.info(result);
 
}

 
...
}

再次啟動服務,並透過 Web Preview 觸發端點:

$ export GOOGLE_CLOUD_PROJECT=`gcloud config list --format 'value(core.project)'`
$
./mvnw -DskipTests spring-boot:run

兩個工作階段視窗中都會顯示記錄訊息,其中追蹤 ID 會由一項服務傳輸至其他服務。

在 Stackdriver Trace 的「追蹤記錄清單」中,您應該會看到第二個追蹤記錄:

您可以按一下新藍色圓點,並查看追蹤記錄詳細資料:

您也可以按一下圖表中的任一跨度,查看跨度詳細資料。

7. 延遲分佈 &成效報表

使用 Stackdriver Trace 做為追蹤資料儲存方式時,Stackdriver Trace 可以使用這些資料來建構延遲時間分佈報表。您需要建立超過 100 個追蹤記錄,才能建立這類報告:

此外,Stackdriver Trace 還可在「數據分析報表」下,自動偵測兩個服務在不同時段的效能迴歸。

8. 摘要

在這個研究室中,您建立了 2 項簡易服務,並透過 Spring Cloud Sleuth 新增分散式追蹤功能,並使用 Spring Cloud GCP 將追蹤記錄資訊轉送至 Stackdriver Trace。

9. 恭喜!

您已經瞭解如何編寫第一個 App Engine 網路應用程式!

瞭解詳情

授權

本作品採用創用 CC 姓名標示 2.0 一般授權。