建置 Spring Cloud Gateway

已完成

在本課程模組中,我們將建置 Spring Cloud Gateway 並將其部署在 Azure Spring 應用程式。

這些閘道可用來將公用 HTTP 流量路由傳送至微服務:

  • 其會處理路由邏輯。
  • 其會保護對微服務的存取,而微服務不會開放公眾使用。
  • 其也可以具有服務品質 (QoS) 功能,例如進行 HTTP 速率限制。

建立 Spring Cloud Gateway

為了建立閘道,我們使用 https://start.spring.io 搭配命令列:

curl https://start.spring.io/starter.tgz -d type=maven-project -d dependencies=cloud-gateway,cloud-eureka,cloud-config-client -d baseDir=todo-gateway -d bootVersion=3.1.5.RELEASE -d javaVersion=17 | tar -xzvf -

注意

我們使用 Cloud GatewayEureka Discovery ClientConfig Client 元件。

設定應用程式

src/main/resources/application.properties 設定檔中,新增下列屬性:

spring.main.allow-bean-definition-overriding=true
spring.cloud.gateway.discovery.locator.enabled=true
  • spring.main.allow-bean-definition-overriding=true 部分是設定 Spring Cloud Gateway,以使用在 Azure Spring 應用程式用戶端程式庫中設定的 Spring Cloud Discovery Server Bean。
  • spring.cloud.gateway.discovery.locator.enabled=true 部分是為了將 Spring Cloud Gateway 設定為使用 Spring Cloud 服務登錄來探索可用的微服務。

在 Azure Spring 應用程式上建立應用程式

和上一個課程模組一樣,請在 Azure Spring 應用程式執行個體中建立特定的 todo-gateway 應用程式。 因為此應用程式是閘道,所以我們會新增 --assign-endpoint 旗標以將其對公眾公開。

az spring app create --name todo-gateway --service "$SPRING_CLOUD_NAME" --resource-group "$RESOURCE_GROUP_NAME" --runtime-version Java_17 --assign-endpoint

部署應用程式

您現在可以建置 todo-gateway 專案,並將其傳送至 Azure Spring 應用程式:

cd todo-gateway
./mvnw clean package -DskipTests
az spring app deploy --name todo-gateway --service "$SPRING_CLOUD_NAME" --resource-group "$RESOURCE_GROUP_NAME" --artifact-path target/demo-0.0.1-SNAPSHOT.jar
cd ..

在雲端中測試專案

  1. 前往您 Azure Spring 應用程式執行個體中的 [應用程式]。

    1. 確認 [todo-gateway] 的註冊狀態顯示為 1/1。 此資訊顯示其已在 Spring Cloud 服務登錄中正確完成註冊。
    2. 選取 [todo-gateway] 以取得微服務的詳細資訊。
  2. 複製/貼上所提供的公用 URL。 請備妥此 URL 以供後續章節使用。

    和微服務一樣,有一個測試端點,但閘道會直接在網際網路上公開,所以我們會使用公用 URL。

閘道連線至 Spring Cloud 服務登錄時,應該會自動開啟通往可用微服務的路由,且其 URL 路徑的格式為 /MICROSERVICE-ID/**:[MICROSERVICE-ID 必須是大寫字母]

執行下列動作來測試 todo-service 微服務端點:curl https://XXXXXXXX-todo-gateway.azuremicroservices.io/TODO-SERVICE/ (以您的 Azure Spring 應用程式執行個體名稱取代 XXXXXXXX)。

和上一個課程模組一樣,此命令的結果應該是一開始插入 MySQL 資料庫的三個項目:

[{"id":"1","description":"First item","done":true},{"id":"2","description":"Second item","done":true},{"id":"3","description":"Third item","done":false}]