官方簡介
該項目提供了一個建立在Spring Ecosystem之上的API網關,包括:Spring 5,Spring Boot 2和Project Reactor。Spring Cloud Gateway旨在提供一種簡單而有效的方式來對API進行路由,并為他們提供切面,例如:安全性,監控/名額 和彈性等。
官方工作原理介紹
用戶端向
spring-cloud-gateway
請求
網關映射處理程式
(gateway handler mapping),如果确認請求與路由比對,則将請求發送到
web處理程式
(gateway web handler),
web處理程式
通過特定于該請求的過濾器鍊處理請求,圖中
filters
被虛線劃分的原因是filters可以在發送代理請求之前(
pre filter
)或之後執行邏輯(
post filter
)。先執行所有
pre filter
邏輯,然後進行請求代理。在請求代理執行完後,執行
post filter
邏輯。
開始使用Spring-Cloud-Gateway
Spring Cloud Gateway依賴Spring Boot和Spring Webflux提供的Netty runtime,是以springboot必須在
2.0或者以上
,springcloud在
Finchley
以上,基本springcloud環境确認後,然後引入:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
路由配置
官網都是用的
yml
配置檔案配置,與
properties
配置檔案配置稍有不同,我這裡全部使用
properties
配置檔案配置。
直接使用注冊中心路由配置
#使用服務發現路由
spring.cloud.gateway.discovery.locator.enabled=true
#服務路由名小寫
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
指定服務配置
#設定路由id
spring.cloud.gateway.routes[0].id=auth-service
#設定路由的uri
spring.cloud.gateway.routes[0].uri=lb://auth-service
#設定路由斷言,代理servicerId為auth-service的/auth/路徑
spring.cloud.gateway.routes[0].predicates[0]= Path=/auth/**
spring.cloud.gateway.routes.predicates
:路由斷言,配置時必須得有一項,不一定是
Path
;
spring.cloud.gateway.routes.uri
:配置路由uri,"lb://‘serviceId’"前代表路由的服務,同時也可以是一個url
編碼服務配置
@Configuration
public class RoutesConfiguration {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes().route(predicateSpec ->
predicateSpec.path("/auth/**").uri("lb://auth-service").id("auth-service")
).build();
}
}