更新時間:2021-12-28 10:51:38 來源:動力節點 瀏覽2193次
在分布式環境中,服務之間需要相互通信。但是,這是服務間通信。我們還有一些用例,我們域外的客戶想要訪問我們的 API 服務。因此,要么我們可以公開所有可由客戶端調用的微服務的地址,要么我們可以創建一個服務網關,將請求路由到各種微服務并響應客戶端。
在這里創建網關是更好的方法。有兩個主要優點
不需要維護每個單獨服務的安全性。
而且,橫切關注點,例如元信息的添加可以在一個地方處理。
Netflix Zuul和Spring Cloud Gateway是兩個著名的 Cloud Gateway,用于處理此類情況。在本教程中,我們將使用 Spring Cloud Gateway。
讓我們以我們一直在使用的 Restaurant 為例。讓我們在我們的兩個服務,即餐廳服務和客戶服務之前添加一個新服務(網關)。首先,讓我們使用以下依賴項更新服務的pom.xm
<dependencies>
<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-gateway</artifactId>
</dependency>
</dependencies>
然后,使用正確的注釋來注釋我們的 Spring 應用程序類,即@EnableDiscoveryClient。
package com.tutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class RestaurantGatewayService{
public static void main(String[] args) {
SpringApplication.run(RestaurantGatewayService.class, args);
}
}
我們使用 @EnableDiscoveryClient 進行注釋,因為我們想使用 Eureka 服務發現來獲取為特定用例提供服務的主機列表
Spring Cloud Gateway 具有三個重要部分。那些是 -
Route - 這些是網關的構建塊,其中包含要轉發請求的 URL 以及應用于傳入請求的謂詞和過濾器。
Predicate - 這些是一組標準,應與要轉發到內部微服務的傳入請求相匹配。例如,只有當傳入的 URL 包含該路徑時,路徑謂詞才會轉發請求。
過濾器- 在將請求發送到內部微服務或響應客戶端之前,您可以在這些地方修改傳入的請求。
讓我們為餐廳和客戶服務的網關編寫一個簡單的配置。
spring:
application:
name: restaurant-gateway-service
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: customers
uri: lb://customer-service
predicates:
- Path=/customer/**
- id: restaurants
uri: lb://restaurant-service
predicates:
- Path=/restaurant/**
server:
port: ${app_port}
eureka:
client:
serviceURL:
defaultZone: http://localhost:8900/eureka
關于上述配置的注意事項
我們啟用了discovery.locator以確保網關可以從 Eureka 服務器讀取。
我們在這里使用了 Path 謂詞來路由請求。這意味著任何以 / customer開頭的請求都將被路由到 Customer Service 并且對于 / restaurant,我們會將該請求轉發給 Restaurant Service。
現在讓我們在網關服務之前設置其他服務
啟動尤里卡服務器
開始客戶服務
啟動餐廳服務
現在,讓我們編譯并執行 Gateway 項目。我們將使用以下命令進行相同的操作
java -Dapp_port=8084 -jar .\target\spring-cloud-gateway-1.0.jar
完成后,我們準備好在端口 8084 上測試網關。讓我們首先點擊 http://localhost:8084/customer/1,我們看到請求被正確路由到客戶服務,我們得到以下輸出
{
"id": 1,
"name": "Jane",
"city": "DC"
}
現在,點擊我們的餐廳 API,即 http://localhost:8084/restaurant/customer/1,我們得到以下輸出
[
{
"id": 1,
"name": "Pandas",
"city": "DC"
},
{
"id": 3,
"name": "Little Italy",
"city": "DC"
}
]
這意味著兩個調用都被正確路由到各自的服務。以上就是關于“SpringCloud網關詳解”的介紹,大家如果想了解更多相關知識,可以關注一下動力節點的Java在線學習,里面的課程內容豐富,由淺到深,適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習