springcloud getaway 簡介及配置(2)


官網: https://spring.io/projects/spring-cloud-gateway

一個比較詳細的參考:Spring cloud gateway 詳解和配置使用:

https://blog.csdn.net/qq_38380025/article/details/102968559?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&dist_request_id=1328603.69312.16152625600677683&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

 

 

參考1:https://www.cnblogs.com/cjsblog/p/11099234.html

1.  為什么是Spring Cloud Gateway

一句話,Spring Cloud已經放棄Netflix Zuul了。現在Spring Cloud中引用的還是Zuul 1.x版本,而這個版本是基於過濾器的,是阻塞IO,不支持長連接。Zuul 2.x版本跟1.x的架構大一樣,性能也有所提升。既然Spring Cloud已經不再集成Zuul 2.x了,那么是時候了解一下Spring Cloud Gateway了。

2.  API網關

API網關是一個服務器,是系統的唯一入口。從面向對象設計的角度看,它與外觀模式類似。API網關封裝了系統內部架構,為每個客戶端提供一個定制的API。它可能還具有其它職責,如身份驗證、監控、負載均衡、緩存、請求分片與管理、靜態響應處理。API網關方式的核心要點是,所有的客戶端和消費端都通過統一的網關接入微服務,在網關層處理所有的非業務功能。通常,網關也是提供REST/HTTP的訪問API。

網關應當具備以下功能:

  • 性能:API高可用,負載均衡,容錯機制。
  • 安全:權限身份認證、脫敏,流量清洗,后端簽名(保證全鏈路可信調用),黑名單(非法調用的限制)。
  • 日志:日志記錄(spainid,traceid)一旦涉及分布式,全鏈路跟蹤必不可少。
  • 緩存:數據緩存。
  • 監控:記錄請求響應數據,api耗時分析,性能監控。
  • 限流:流量控制,錯峰流控,可以定義多種限流規則。
  • 灰度:線上灰度部署,可以減小風險。
  • 路由:動態路由規則。

目前,比較流行的網關有:Nginx 、 Kong 、Orange等等,還有微服務網關Zuul 、Spring Cloud Gateway等等

對於 API Gateway,常見的選型有基於 Openresty 的 Kong、基於 Go 的 Tyk 和基於 Java 的 Zuul。這三個選型本身沒有什么明顯的區別,主要還是看技術棧是否能滿足快速應用和二次開發。

以上說的這些功能,這些開源的網關組件都有,或者借助Lua也能實現,比如:Nginx + Lua

那要Spring Cloud Gateway還有什么用呢?

其實,我個人理解是這樣的:

  • 像Nginx這類網關,性能肯定是沒得說,它適合做那種門戶網關,是作為整個全局的網關,是對外的,處於最外層的;而Gateway這種,更像是業務網關,主要用來對應不同的客戶端提供服務的,用於聚合業務的。各個微服務獨立部署,職責單一,對外提供服務的時候需要有一個東西把業務聚合起來。
  • 像Nginx這類網關,都是用不同的語言編寫的,不易於擴展;而Gateway就不同,它是用Java寫的,易於擴展和維護
  • Gateway這類網關可以實現熔斷、重試等功能,這是Nginx不具備的

所以,你看到的網關可能是這樣的:

 

 

 2.1.  Netflix Zuul 1.x  VS  Netflix Zuul 2.x

 

 

 

3.  Spring Cloud Gateway

3.1.  特性

  • 基於Spring Framework 5、Project Reactor和Spring Boot 2.0構建
  • 能夠在任意請求屬性上匹配路由
  • predicates(謂詞) 和 filters(過濾器)是特定於路由的
  • 集成了Hystrix斷路器
  • 集成了Spring Cloud DiscoveryClient
  • 易於編寫謂詞和過濾器
  • 請求速率限制
  • 路徑重寫

3.2.  術語

Route : 路由是網關的基本組件。它由ID、目標URI、謂詞集合和過濾器集合定義。如果聚合謂詞為true,則匹配路由

Predicate : This is a Java 8 Function Predicate

Filter : 是GatewayFilter的一個實例,在這里,可以在發送下游請求之前或之后修改請求和響應

3.3.  原理

 

 

 

客戶端向Spring Cloud Gateway發出請求。如果Gateway Handler Mapping確定請求與路由匹配,則將其發送給Gateway Web Handler。這個Handler運行通過特定於請求的過濾器鏈發送請求。過濾器可以在發送代理請求之前或之后執行邏輯。執行所有的“pre”過濾邏輯,然后發出代理請求,最后執行“post”過濾邏輯。

3.4.  Route Predicate Factories

  • Spring Cloud Gateway 包含許多內置的 Route Predicate Factories
  • 所有這些predicates用於匹配HTTP請求的不同屬性
  • 多個 Route Predicate Factories 可以通過邏輯與(and)結合起來一起使用

3.4.1.  After Route Predicate Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]
復制代碼

這個路由匹配“美國丹佛時間2017-01-20 17:42”之后的任意請求

3.4.2.  Header Route Predicate Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
復制代碼

這個路由匹配“請求頭包含X-Request-Id並且其值匹配正則表達式\d+”的任意請求

3.4.3.  Method Route Predicate Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET
復制代碼

這個路由匹配任意GET請求

3.4.4.  Path Route Predicate Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Path=/foo/{segment},/bar/{segment}
復制代碼

這個路由匹配這樣路徑的請求,比如:/foo/1 或 /foo/bar 或 /bar/baz

3.4.5.  Query Route Predicate Factory

這個Predicate有兩個參數:一個必須的參數名和一個可選的正則表達式

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=baz
復制代碼

這個路由匹配“查詢參數中包含baz”的請求

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=foo, ba.
復制代碼

這個路由匹配“查詢參數中包含foo,並且其參數值滿足正則表達式ba.”的請求,比如:bar,baz

3.4.6.  RemoteAddr Route Predicate Factory

這個路由接受一個IP(IPv4或IPv6)地址字符串。例如:192.168.0.1/16,其中192.168.0.1,16是子網掩碼

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24
復制代碼

這里路由匹配遠程地址是這樣的請求,例如:192.168.1.10

3.5.  GatewayFilter Factories(網關過濾器)

路由過濾器允許以某種方式修改傳入的HTTP請求或傳出HTTP響應。路由過濾器的作用域是特定的路由。Spring Cloud Gateway包含許多內置的網關過濾器工廠。

3.5.1.  AddRequestHeader GatewayFilter Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-Foo, Bar
復制代碼

對於所有匹配的請求,將會給傳給下游的請求添加一個請求頭 X-Request-Foo:Bar

3.5.2.  AddRequestParameter GatewayFilter Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=foo, bar
復制代碼

對於所有匹配的請求,將給傳給下游的請求添加一個查詢參數 foo=bar

3.5.3.  AddResponseHeader GatewayFilter Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Foo, Bar
復制代碼

對於所有匹配的請求,添加一個響應頭 X-Response-Foo:Bar

3.5.4.  Hystrix GatewayFilter Factory

Hystrix網關過濾器允許你將斷路器引入網關路由,保護你的服務免受級聯失敗的影響,並在下游發生故障時提供預備響應。

為了啟用Hystrix網關過濾器,你需要引入 spring-cloud-starter-netflix-hystrix

Hystrix網關過濾器需要一個name參數,這個name是HystrixCommand的名字

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: https://example.org
        filters:
        - Hystrix=myCommandName
復制代碼

給這個過濾器包裝一個名字叫myCommandName的HystrixCommand

Hystrix網關過濾器也接受一個可選的參數fallbackUri,但是目前只支持forward:前綴的URL。也就是說,如果這個fallback被調用,請求將被重定向到匹配的這個URL。

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingserviceendpoint
        filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/incaseoffailureusethis
        - RewritePath=/consumingserviceendpoint, /backingserviceendpoint
復制代碼

當fallback被調用的時候,請求將被重定向到/incaseoffailureusethis

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: Hystrix
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
復制代碼

在這個例子中,專門定義了一個端點來處理/fallback請求,它在localhost:9994上。也就是說,當fallback被調用的時候將重定向到http://localhost:9994/fallback

3.5.5.  PrefixPath GatewayFilter Factory

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath
復制代碼

所有匹配的請求都將加上前綴/mypath。例如,如果請求是/hello,那么經過這個過濾器后,發出去的請求變成/mypath/hello

3.5.6.  RequestRateLimiter GatewayFilter Factory

RequestRateLimiter網關過濾器使用一個RateLimiter實現來決定是否當前請求可以繼續往下走。如果不能,默認將返回HTTP 429 - Too Many Requests

這個過濾器接受一個可選的參數keyResolver,這個參數是一個特定的rate limiter

keyResolver是實現了KeyResolver接口的一個Bean。

在配置的時候,使用SpEL按名稱引用Bean。#{@myKeyResolver}是一個SpEL表達式,表示引用名字叫myKeyResolver的Bean。

KeyResolver.java

public interface KeyResolver {
     Mono<String> resolve(ServerWebExchange exchange); }

KeyResolver默認的實現是PrincipalNameKeyResolver,它從ServerWebExchange中檢索Principal,並調用Principal.getName()方法。 

默認情況下,如果KeyResolver沒有找到一個key,那么請求將會被denied(譯:否認,拒絕)。這種行為可以通過spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key (true or false) 和 spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code 屬性來進行調整. 

Redis RateLimiter

需要引用 spring-boot-starter-data-redis-reactive

這個邏輯使用令牌桶算法

  • redis-rate-limiter.replenishRate : 允許用戶每秒處理多少個請求。這是令牌桶被填充的速率。
  • redis-rate-limiter.burstCapacity : 用戶在一秒鍾內允許執行的最大請求數。這是令牌桶可以容納的令牌數量。將此值設置為0將阻塞所有請求。

一個穩定的速率是通過將replenishRate 和 burstCapacity設為相同的值來實現的。也可以將burstCapacity設得比replenishRate大,以應對臨時爆發的流量。在這種情況下,需要允許速率限制器在突發事件之間間隔一段時間,因為連續兩次突發事件將導致丟棄請求(HTTP 429 - Too Many Requests)

application.yml

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
復制代碼

Config.java

@Bean
 KeyResolver userKeyResolver() {
     return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user")); }

 

這里定義了每個用戶的請求速率限制為10。允許使用20個請求,但是在接下來的一秒中,只有10個請求可用。

這個例子中只是簡單地從請求參數中獲取"user",在實際生產環境中不建議這么做。

我們也可以通過實現RateLimiter接口來自定義,這個時候,在配置中我們就需要引用這個Bean,例如:#{@myRateLimiter} 

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"
復制代碼

3.5.7.  Default Filters

如果你想要添加一個過濾器並且把它應用於所有路由的話,你可以用spring.cloud.gateway.default-filters。這個屬性接受一個過濾器列表。

spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Foo, Default-Bar
      - PrefixPath=/httpbin

3.6.  Global Filters(全局過濾器)

GlobalFilter接口的方法簽名和GatewayFilter相同。這些是有條件地應用於所有路由的特殊過濾器。

3.6.1.  GlobalFilter和GatewayFilter的順序

當一個請求過來的時候,將會添加所有的GatewayFilter實例和所有特定的GatewayFilter實例到過濾器鏈上。過濾器鏈按照org.springframework.core.Ordered接口對該鏈路上的過濾器進行排序。你可以通過實現接口中的getOrder()方法或者使用@Order注解。

Spring Cloud Gateway將過濾器執行邏輯分為“pre”和“post”階段。優先級最高的過濾器將會是“pre”階段中的第一個過濾器,同時它也將是“post”階段中的最后一個過濾器。

ExampleConfiguration.java

 1 @Bean
 2 @Order(-1)
 3 public GlobalFilter a() {
 4     return (exchange, chain) -> {
 5         log.info("first pre filter");
 6         return chain.filter(exchange).then(Mono.fromRunnable(() -> {
 7             log.info("third post filter");
 8         }));
 9     };
10 }
11 
12 @Bean
13 @Order(0)
14 public GlobalFilter b() {
15     return (exchange, chain) -> {
16         log.info("second pre filter");
17         return chain.filter(exchange).then(Mono.fromRunnable(() -> {
18             log.info("second post filter");
19         }));
20     };
21 }
22 
23 @Bean
24 @Order(1)
25 public GlobalFilter c() {
26     return (exchange, chain) -> {
27         log.info("third pre filter");
28         return chain.filter(exchange).then(Mono.fromRunnable(() -> {
29             log.info("first post filter");
30         }));
31     };
32 }

3.6.2.  LoadBalancerClient Filter

LoadBalancerClientFilter查找exchange屬性中查找ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR一個URI。如果url符合lb schema(例如:lb://myservice),那么它將使用Spring Cloud LoadBalancerClient 來解析這個名字到一個實際的主機和端口,並替換URI中相同的屬性。原始url中未被修改的部分被附加到ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR屬性列表中。

application.yml

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: myRoute
        uri: lb://service
        predicates:
        - Path=/service/**
復制代碼

默認情況下,當一個服務實例在LoadBalancer中沒有找到時,將返回503。你可以通過配置spring.cloud.gateway.loadbalancer.use404=true來讓它返回404。

 

3.7.  配置

RouteDefinitionLocator.java 

1 public interface RouteDefinitionLocator {
2 	Flux<RouteDefinition> getRouteDefinitions();
3 }

默認情況下,PropertiesRouteDefinitionLocator通過@ConfigurationProperties機制加載屬性

下面兩段配置是等價的

復制代碼
spring:
  cloud:
    gateway:
      routes:
      - id: setstatus_route
        uri: https://example.org
        filters:
        - name: SetStatus
          args:
            status: 401
      - id: setstatusshortcut_route
        uri: https://example.org
        filters:
        - SetStatus=401
復制代碼

下面用Java配置

 

GatewaySampleApplication.java 

 1 // static imports from GatewayFilters and RoutePredicates
 2 @Bean
 3 public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
 4     return builder.routes()
 5             .route(r -> r.host("**.abc.org").and().path("/image/png")
 6                 .filters(f ->
 7                         f.addResponseHeader("X-TestHeader", "foobar"))
 8                 .uri("http://httpbin.org:80")
 9             )
10             .route(r -> r.path("/image/webp")
11                 .filters(f ->
12                         f.addResponseHeader("X-AnotherHeader", "baz"))
13                 .uri("http://httpbin.org:80")
14             )
15             .route(r -> r.order(-1)
16                 .host("**.throttle.org").and().path("/get")
17                 .filters(f -> f.filter(throttle.apply(1,
18                         1,
19                         10,
20                         TimeUnit.SECONDS)))
21                 .uri("http://httpbin.org:80")
22             )
23             .build();
24 }

這種風格允許自定義更多的謂詞斷言,默認是邏輯與(and)。你也可以用and() , or() , negate() 

再來一個例子

 1 @SpringBootApplication
 2 public class DemogatewayApplication {
 3 	@Bean
 4 	public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
 5 		return builder.routes()
 6 			.route("path_route", r -> r.path("/get")
 7 				.uri("http://httpbin.org"))
 8 			.route("host_route", r -> r.host("*.myhost.org")
 9 				.uri("http://httpbin.org"))
10 			.route("hystrix_route", r -> r.host("*.hystrix.org")
11 				.filters(f -> f.hystrix(c -> c.setName("slowcmd")))
12 				.uri("http://httpbin.org"))
13 			.route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
14 				.filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
15 				.uri("http://httpbin.org"))
16 			.route("limit_route", r -> r
17 				.host("*.limited.org").and().path("/anything/**")
18 				.filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter())))
19 				.uri("http://httpbin.org"))
20 			.build();
21 	}
22 }

3.8.  CORS配置

復制代碼
spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://docs.spring.io"
            allowedMethods:
            - GET
復制代碼

上面的例子中,所有原始為docs.spring.io的GET請求均被允許跨域請求。

 

 

 

@Bean
2 KeyResolver userKeyResolver() {
3     return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
4 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM