日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Cloud GatewayAPI网关服务

發布時間:2025/3/15 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Cloud GatewayAPI网关服务 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、Gateway 簡介

Gateway是在Spring生態系統之上構建的API網關服務,基于Spring 5,Spring Boot 2和 Project Reactor等技術。Gateway旨在提供一種簡單而有效的方式來對API進行路由,以及提供一些強大的過濾器功能, 例如:熔斷、限流、重試等。
Spring Cloud Gateway 具有如下特性:

  • 基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 進行構建;
  • 動態路由:能夠匹配任何請求屬性;
  • 可以對路由指定 Predicate(斷言)和 Filter(過濾器);
  • 集成Hystrix的斷路器功能;
  • 集成 Spring Cloud 服務發現功能;
  • 易于編寫的 Predicate(斷言)和 Filter(過濾器);
  • 請求限流功能;
  • 支持路徑重寫。

二、相關概念

  • Route(路由):路由是構建網關的基本模塊,它由ID,目標URI,一系列的斷言和過濾器組成,如果斷言為true則匹配該路由;
  • Predicate(斷言):指的是Java 8 的 Function Predicate。
    輸入類型是Spring框架中的ServerWebExchange。
    這使開發人員可以匹配HTTP請求中的所有內容,例如請求頭或請求參數。如果請求與斷言相匹配,則進行路由;
  • Filter(過濾器):指的是Spring框架中GatewayFilter的實例,使用過濾器,可以在請求被路由前后對請求進行修改。

三、創建gateway模塊

這里我們創建一個api-gateway模塊來演示Gateway的常用功能。

在pom.xml中添加相關依賴

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId> </dependency>

Gateway 提供了兩種不同的方式用于配置路由,

  • 一種是通過yml文件來配置,
  • 另一種是通過Java Bean來配置
  • 使用yml配置

在application.yml中進行配置:

server:port: 2007 spring:cloud:gateway:discovery:locator:enabled: true #開啟從注冊中心動態創建路由的功能,利用微服務名進行路由routes:- id: user-service #路由的ID,沒有固定規則但要求唯一,建議配合服務名# uri: http://localhost:8008 #匹配后提供服務的路由地址uri: lb://user-service #匹配后提供服務的路由地址,進行負載均衡predicates:- Path=/user/** # 斷言,路徑相匹配的進行路由- id: payment_routh2 #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名#uri: http://localhost:8001 #匹配后提供服務的路由地址uri: lb://payment-service #匹配后提供服務的路由地址predicates:- Path=/payment/lb/** # 斷言,路徑相匹配的進行路由#- After=2021-05-21T15:51:37.485+08:00[Asia/Shanghai]#- Cookie=username,xxxx#- Header=X-Request-Id, \d+ # 請求頭要有X-Request-Id屬性并且值為整數的正則表達式
  • java Bean配置方式
    添加相關配置類,并配置一個RouteLocator對象:
/*** @author Cristianoxm*/ @Configuration public class GateWayConfig {@Beanpublic RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();return routes.route("user-service1", r -> r.path("/user/getByUsername").uri("http://localhost:8088/user/getByUsername")).build();} }

四、啟動nacos,user-service和gateway服務


nacos控制面板:

并調用該地址測試:http://localhost:2007/user/1

因為我采用了負載均衡策略,所以可以看到,8086的微服務,和8088的微服務被輪詢訪問


訪問:http://localhost:2007/user/getByUsername?username=andy

五、Route Predicate 的使用

Spring Cloud Gateway將路由匹配作為Spring WebFlux HandlerMapping基礎架構的一部分。 Spring Cloud Gateway包括許多內置的Route Predicate工廠。 所有這些Predicate都與HTTP請求的不同屬性匹配。 多個Route Predicate工廠可以進行組合,下面我們來介紹下一些常用的Route Predicate。
注意:Predicate中提到的配置都在application-predicate.yml文件中進行修改,并用該配置啟動api-gateway服務。

  • After Route Predicate:在指定時間之后的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: after_routeuri: ${service-url.user-service}predicates:- After=2019-09-24T16:30:00+08:00[Asia/Shanghai]
  • Before Route Predicate:在指定時間之前的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: before_routeuri: ${service-url.user-service}predicates:- Before=2019-09-24T16:30:00+08:00[Asia/Shanghai]
  • Between Route Predicate:在指定時間區間內的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: before_routeuri: ${service-url.user-service}predicates:- Between=2019-09-24T16:30:00+08:00[Asia/Shanghai], 2019-09-25T16:30:00+08:00[Asia/Shanghai]
  • Cookie Route Predicate:帶有指定Cookie的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: cookie_routeuri: ${service-url.user-service}predicates:- Cookie=username,macro

    使用curl工具發送帶有cookie為username=macro的請求可以匹配該路由。

    curl http://localhost:9201/user/1 --cookie "username=macro"
  • Header Route Predicate:帶有指定請求頭的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: header_routeuri: ${service-url.user-service}predicates:- Header=X-Request-Id, \d+

    使用curl工具發送帶有請求頭為X-Request-Id:123的請求可以匹配該路由。

    curl http://localhost:9201/user/1 -H "X-Request-Id:123"
  • Host Route Predicate
    帶有指定Host的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: host_routeuri: ${service-url.user-service}predicates:- Host=**.xxxxxx.com

    使用curl工具發送帶有請求頭為Host:www.xxxxx.com的請求可以匹配該路由。

    curl http://localhost:9201/user/1 -H "Host:www.xxxxx.com"
  • Method Route Predicate:發送指定方法的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: method_routeuri: ${service-url.user-service}predicates:- Method=GET

    使用curl工具發送GET請求可以匹配該路由。

    curl http://localhost:9201/user/1

    使用curl工具發送POST請求無法匹配該路由。

    curl -X POST http://localhost:9201/user/1
  • Path Route Predicate:發送指定路徑的請求會匹配該路由。
  • spring:cloud:gateway:routes:- id: path_routeuri: ${service-url.user-service}/user/{id}predicates:- Path=/user/{id}

    使用curl工具發送/user/1路徑請求可以匹配該路由。

    curl http://localhost:9201/user/1

    使用curl工具發送/abc/1路徑請求無法匹配該路由。

    curl http://localhost:9201/abc/1
  • Query Route Predicate:帶指定查詢參數的請求可以匹配該路由。
  • spring:cloud:gateway:routes:- id: query_routeuri: ${service-url.user-service}/user/getByUsernamepredicates:- Query=username

    使用curl工具發送帶username=macro查詢參數的請求可以匹配該路由。

    curl http://localhost:9201/user/getByUsername?username=macro

    使用curl工具發送帶不帶查詢參數的請求無法匹配該路由。

    curl http://localhost:9201/user/getByUsername
  • RemoteAddr Route Predicate:從指定遠程地址發起的請求可以匹配該路由。
  • spring:cloud:gateway:routes:- id: remoteaddr_routeuri: ${service-url.user-service}predicates:- RemoteAddr=192.168.1.1/24

    使用curl工具從192.168.1.1發起請求可以匹配該路由。

    curl http://localhost:9201/user/1
  • Weight Route Predicate:使用權重來路由相應請求。
    以下表示有80%的請求會被路由到localhost:8201,20%會被路由到localhost:8202。
  • spring:cloud:gateway:routes:- id: weight_highuri: http://localhost:8201predicates:- Weight=group1, 8- id: weight_lowuri: http://localhost:8202predicates:- Weight=group1, 2

    六、Route Filter 的使用

    路由過濾器可用于修改進入的HTTP請求和返回的HTTP響應,路由過濾器只能指定路由進行使用。Spring Cloud Gateway 內置了多種路由過濾器,他們都由GatewayFilter的工廠類來產生,下面我們介紹下常用路由過濾器的用法。

  • AddRequestParameter GatewayFilter:給請求添加參數的過濾器。
  • spring:cloud:gateway:routes:- id: add_request_parameter_routeuri: http://localhost:8201filters:- AddRequestParameter=username, macropredicates:- Method=GET

    以上配置會對GET請求添加username=macro的請求參數,通過curl工具使用以下命令進行測試。

    curl http://localhost:9201/user/getByUsername

    相當于發起該請求:

    curl http://localhost:8201/user/getByUsername?username=macro
  • StripPrefix GatewayFilter:對指定數量的路徑前綴進行去除的過濾器。
  • spring:cloud:gateway:routes:- id: strip_prefix_routeuri: http://localhost:8201predicates:- Path=/user-service/**filters:- StripPrefix=2

    以上配置會把以/user-service/開頭的請求的路徑去除兩位,通過curl工具使用以下命令進行測試。

    curl http://localhost:9201/user-service/a/user/1

    相當于發起該請求:

    curl http://localhost:8201/user/1
  • PrefixPath GatewayFilter:與StripPrefix過濾器恰好相反,會對原有路徑進行增加操作的過濾器。
  • spring:cloud:gateway:routes:- id: prefix_path_routeuri: http://localhost:8201predicates:- Method=GETfilters:- PrefixPath=/user

    以上配置會對所有GET請求添加/user路徑前綴,通過curl工具使用以下命令進行測試。

    curl http://localhost:9201/1

    相當于發起該請求:

    curl http://localhost:8201/user/1
  • Hystrix GatewayFilter:Hystrix 過濾器允許你將斷路器功能添加到網關路由中,使你的服務免受級聯故障的影響,并提供服務降級處理。配合Hystrix實現流控
  • 要開啟斷路器功能,我們需要在pom.xml中添加Hystrix的相關依賴:

    <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>

    然后添加相關服務降級的處理類:

    @RestController public class FallbackController {@GetMapping("/fallback")public Object fallback() {Map<String,Object> result = new HashMap<>();result.put("data",null);result.put("message","Get request fallback!");result.put("code",500);return result;} }

    在application-filter.yml中添加相關配置,當路由出錯時會轉發到服務降級處理的控制器上:

    spring:cloud:gateway:routes:- id: hystrix_routeuri: http://localhost:8201predicates:- Method=GETfilters:- name: Hystrixargs:name: fallbackcmdfallbackUri: forward:/fallback

    關閉user-service,調用該地址進行測試:http://localhost:9201/user/1 ,發現已經返回了服務降級的處理信息。

  • RequestRateLimiter GatewayFilter:RequestRateLimiter 過濾器可以用于限流,使用RateLimiter實現來確定是否允許當前請求繼續進行,如果請求太大默認會返回HTTP 429-太多請求狀態。
  • 在pom.xml中添加相關依賴:

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>

    添加限流策略的配置類,這里有兩種策略一種是根據請求參數中的username進行限流,另一種是根據訪問IP進行限流;

    @Configuration public class RedisRateLimiterConfig {@BeanKeyResolver userKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("username"));}@Beanpublic KeyResolver ipKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());} }

    我們使用Redis來進行限流,所以需要添加Redis和RequestRateLimiter的配置,這里對所有的GET請求都進行了按IP來限流的操作;

    server:port: 9201 spring:redis:host: localhostpassword: 123456port: 6379cloud:gateway:routes:- id: requestratelimiter_routeuri: http://localhost:8201filters:- name: RequestRateLimiterargs:redis-rate-limiter.replenishRate: 1 #每秒允許處理的請求數量redis-rate-limiter.burstCapacity: 2 #每秒最大處理的請求數量key-resolver: "#{@ipKeyResolver}" #限流策略,對應策略的Beanpredicates:- Method=GET logging:level:org.springframework.cloud.gateway: debug

    多次請求該地址:http://localhost:9201/user/1 ,會返回狀態碼為429的錯誤;

  • Retry GatewayFilter:對路由請求進行重試的過濾器,可以根據路由請求返回的HTTP狀態碼來確定是否進行重試。
  • 修改配置文件:

    spring:cloud:gateway:routes:- id: retry_routeuri: http://localhost:8201predicates:- Method=GETfilters:- name: Retryargs:retries: 1 #需要進行重試的次數statuses: BAD_GATEWAY #返回哪個狀態碼需要進行重試,返回狀態碼為5XX進行重試backoff:firstBackoff: 10msmaxBackoff: 50msfactor: 2basedOnPreviousValue: false

    文章轉自

    更多關于gateway的配置

    總結

    以上是生活随笔為你收集整理的Spring Cloud GatewayAPI网关服务的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。