前言
在微服務架構中,API 網關(API Gateway)扮演著非常重要的角色。它負責接收客戶端請求,并根據預定義的規則將請求路由到對應的后端服務。Spring Cloud Gateway 是 Spring 官方推出的一款高性能網關,支持動態路由、負載均衡、限流等功能。本文將詳細介紹 Spring Cloud Gateway 的工作原理、配置方式以及如何實現請求分發,并附帶源碼和 UML 圖示。
一、Spring Cloud Gateway 的核心概念
1.1 核心組件
- Route(路由):網關的基本構建塊,包含一個 ID、目標 URI 和一組斷言(Predicate)和過濾器(Filter)。只有當請求滿足斷言條件時,才會被路由到指定的目標服務。
- Predicate(斷言):用于匹配 HTTP 請求中的特定條件,例如路徑、方法、頭信息等。
- Filter(過濾器):對請求和響應進行處理,如修改請求頭、添加日志、鑒權等。
1.2 工作流程圖
以下是 Spring Cloud Gateway 的工作流程圖:
二、配置 Spring Cloud Gateway
2.1 引入依賴
在 pom.xml
文件中添加以下依賴:
<dependencies><!-- Spring Cloud Gateway --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- Spring Boot WebFlux --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><!-- Spring Cloud Load Balancer (用于負載均衡) --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency>
</dependencies>
2.2 配置路由規則
在 application.yml
中定義路由規則。以下是一個簡單的示例:
spring:cloud:gateway:routes:- id: user_service_routeuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- AddRequestHeader=X-Gateway-Version, v1.0- id: order_service_routeuri: lb://ORDER-SERVICEpredicates:- Path=/order/**filters:- AddResponseHeader=X-Gateway-Version, v1.0
配置說明:
id
:路由的唯一標識符。uri
:目標服務地址,lb://
表示使用負載均衡器(Load Balancer)。predicates
:定義匹配條件,例如路徑/user/**
。filters
:定義請求或響應的處理邏輯,例如添加請求頭或響應頭。
三、實現請求分發的核心邏輯
3.1 動態路由匹配
Spring Cloud Gateway 使用 Predicate
來匹配請求。以下是一個基于路徑的分發邏輯示例:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;@Configuration
public class GatewayConfig {@Beanpublic RouteLocator customRouteLocator(RouteLocatorBuilder builder) {return builder.routes().route("user_service_route", r -> r.path("/user/**").filters(f -> f.addRequestHeader("X-Gateway-Version", "v1.0")).uri("lb://USER-SERVICE")).route("order_service_route", r -> r.path("/order/**").filters(f -> f.addResponseHeader("X-Gateway-Version", "v1.0")).uri("lb://ORDER-SERVICE")).build();}
}
代碼解析:
RouteLocatorBuilder
用于構建路由規則。.path("/user/**")
匹配以/user/
開頭的路徑。.uri("lb://USER-SERVICE")
將請求轉發到注冊中心的服務USER-SERVICE
。
3.2 負載均衡
Spring Cloud Gateway 內置了對負載均衡的支持,通過 lb://
協議可以實現服務發現和負載均衡。
示例場景:
假設有兩個用戶服務實例 USER-SERVICE-1
和 USER-SERVICE-2
注冊到了 Eureka 注冊中心,Gateway 會根據負載均衡策略自動選擇一個實例來處理請求。
3.3 自定義過濾器
除了內置過濾器,您還可以自定義過濾器來實現特定功能,例如鑒權、日志記錄等。
以下是一個自定義過濾器的示例:
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;@Component
public class LoggingFilter extends AbstractGatewayFilterFactory<LoggingFilter.Config> {public LoggingFilter() {super(Config.class);}@Overridepublic GatewayFilter apply(Config config) {return (exchange, chain) -> {System.out.println("請求路徑:" + exchange.getRequest().getPath());return chain.filter(exchange).then(Mono.fromRunnable(() -> {System.out.println("響應狀態碼:" + exchange.getResponse().getStatusCode());}));};}public static class Config {// 可以在這里定義配置參數}
}
使用自定義過濾器:
在 application.yml
中引用自定義過濾器:
spring:cloud:gateway:routes:- id: user_service_routeuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- LoggingFilter
四、完整示例
以下是一個完整的 Spring Cloud Gateway 示例,包括服務注冊與發現、負載均衡和自定義過濾器。
4.1 項目結構
gateway-service/
├── src/main/java/com/example/gateway/
│ ├── GatewayApplication.java
│ ├── GatewayConfig.java
│ └── LoggingFilter.java
├── src/main/resources/
│ └── application.yml
└── pom.xml
4.2 啟動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class GatewayApplication {public static void main(String[] args) {SpringApplication.run(GatewayApplication.class, args);}
}
4.3 配置文件
server:port: 8080spring:application:name: gateway-servicecloud:gateway:routes:- id: user_service_routeuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- LoggingFilter- id: order_service_routeuri: lb://ORDER-SERVICEpredicates:- Path=/order/**filters:- AddResponseHeader=X-Gateway-Version, v1.0eureka:client:service-url:defaultZone: http://localhost:8761/eureka/
五、總結
通過本文,我們詳細介紹了 Spring Cloud Gateway 的核心概念、配置方式以及如何實現請求分發。以下是關鍵點總結:
- 核心組件:Route、Predicate 和 Filter 是 Gateway 的三大核心組件。
- 動態路由:通過
Path
斷言實現請求分發。 - 負載均衡:結合 Eureka 注冊中心實現服務發現和負載均衡。
- 自定義過濾器:擴展 Gateway 功能,實現日志記錄、鑒權等需求。
希望本文能幫助您快速上手 Spring Cloud Gateway,并將其應用到實際項目中。如果您有任何問題或建議,請隨時留言交流!
參考資料
- Spring Cloud Gateway 官方文檔
- Spring Cloud Netflix Eureka 文檔