中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

吃什么補(bǔ)腎虛效果最好食物焦作整站優(yōu)化

吃什么補(bǔ)腎虛效果最好食物,焦作整站優(yōu)化,站長統(tǒng)計(jì)向日葵app下載,wordpress之外的博客軟件Spring Cloud Gateway路由 文章目錄 1. 前言2. Gateway路由的基本概念3. 三種路由1. 靜態(tài)路由2. 動(dòng)態(tài)路由1. 利用外部存儲(chǔ)2. API動(dòng)態(tài)路由 3. 服務(wù)發(fā)現(xiàn)路由(自動(dòng)路由)3.1. 配置方式3.2 自動(dòng)路由(服務(wù)發(fā)現(xiàn))原理核心源碼GatewayDiscoveryClientAutoConfigur…

Spring Cloud Gateway路由

文章目錄

  • 1. 前言
  • 2. Gateway路由的基本概念
  • 3. 三種路由
    • 1. 靜態(tài)路由
    • 2. 動(dòng)態(tài)路由
      • 1. 利用外部存儲(chǔ)
      • 2. API動(dòng)態(tài)路由
    • 3. 服務(wù)發(fā)現(xiàn)路由(自動(dòng)路由)
      • 3.1. 配置方式
      • 3.2 自動(dòng)路由(服務(wù)發(fā)現(xiàn))原理
        • 核心源碼
          • GatewayDiscoveryClientAutoConfiguration
          • `DiscoveryClientRouteDefinitionLocator`核心方法`getRouteDefinitions`
  • 4. Gateway路由的核心組件
    • 4.1 路由斷言
      • 組合并生效相當(dāng)于并且的關(guān)系
      • 如果要或的關(guān)系需要分配多個(gè)路由
    • 4.2 路由過濾器
      • 路由過濾器概念
      • 路由過濾器工廠
      • 內(nèi)置路由過濾器
      • 自定義路由過濾器
  • 5. 路由的動(dòng)態(tài)刷新
    • 5.1. 添加依賴
    • 5.2. 配置application.yml
    • 5.3. 創(chuàng)建Config Server
    • 5.4. 在遠(yuǎn)程Git倉庫中添加配置文件
    • 5.5. 啟動(dòng)Gateway服務(wù)
    • 5.6. 動(dòng)態(tài)刷新路由信息
  • 6. 處理路由失敗和異常
      • 6.1 處理請求失敗和異常
      • 6.2 配置回退和重試策略
  • 7. 高級路由功能
  • 8. 參考文檔

1. 前言

其實(shí)Spring Cloud Gateway2.x 的官網(wǎng)文檔寫的已經(jīng)很全面了,如果想要了解,可以訪問 《Spring Cloud Gateway》

在這里插入圖片描述

Spring Cloud Gateway是一個(gè)基于Spring Boot構(gòu)建的API網(wǎng)關(guān),主要用于微服務(wù)架構(gòu)中。它提供了一種簡單而高效的方式來對請求進(jìn)行路由、過濾和轉(zhuǎn)發(fā),從而實(shí)現(xiàn)對服務(wù)的統(tǒng)一訪問入口和流量管理。Spring Cloud Gateway通過一個(gè)高度可配置的路由規(guī)則集,支持各種復(fù)雜的請求處理場景。

與傳統(tǒng)的API網(wǎng)關(guān)(如Zuul)相比,Spring Cloud Gateway提供了更好的性能和豐富的功能。它基于響應(yīng)式編程模型(Reactive)和Spring WebFlux框架構(gòu)建,能夠提供非阻塞的異步I/O處理,并且能夠很好地與其他Spring Cloud組件進(jìn)行集成。此外,Spring Cloud Gateway還提供了很多現(xiàn)成的功能,如負(fù)載均衡、熔斷、限流等,可以幫助開發(fā)者快速搭建一個(gè)完善的API網(wǎng)關(guān)。
在這里插入圖片描述
圖片來自Spring Cloud Gateway2 官網(wǎng) https://cloud.spring.io/spring-cloud-gateway/2.0.x/single/spring-cloud-gateway.html

2. Gateway路由的基本概念

  • 2.1 路由的定義和作用
    路由是一個(gè)HTTP請求的處理過程。在Spring Cloud Gateway中,每個(gè)請求都會(huì)經(jīng)過一系列的過濾器,最后轉(zhuǎn)發(fā)到目標(biāo)URI。

路由配置由三部分組成:ID、目標(biāo)URI、一系列的斷言和過濾器。ID是路由的唯一標(biāo)識,目標(biāo)URI是請求的最終目的地,斷言是用來匹配HTTP請求的規(guī)則,過濾器是用來處理HTTP請求的組件。

在Spring Cloud Gateway中配置路由有兩種方式:通過配置文件和通過代碼。

  1. 通過配置文件配置路由:

在application.yml文件中添加如下配置:

spring:cloud:gateway:routes:- id: user_routeuri: http://localhost:8080predicates:- Path=/user/**

以上面的配置為例,id為user_route的路由會(huì)匹配所有路徑為/user/的請求,然后將其轉(zhuǎn)發(fā)到http://localhost:8080。

  1. 通過代碼配置路由:

在配置類中添加如下配置:

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {return builder.routes().route("user_route", r -> r.path("/user/**").uri("http://localhost:8080")).build();
}

以上面的配置為例,id為user_route的路由會(huì)匹配所有路徑為/user/的請求,然后將其轉(zhuǎn)發(fā)到http://localhost:8080。

  • 2.2 如何在Spring Cloud Gateway中配置路由

3. 三種路由

根據(jù)路由的創(chuàng)建方式和使用場景,可以將路由分類為以下三種:

1. 靜態(tài)路由

在Spring Cloud Gateway啟動(dòng)時(shí),通過配置文件或Java代碼定義的路由規(guī)則。這些路由規(guī)則在運(yùn)行時(shí)是不可修改的。
可以通過配置文件定義靜態(tài)路由:這段配置會(huì)將所有以/user開始的請求轉(zhuǎn)發(fā)到http://localhost:8080。

spring:cloud:gateway:routes:- id: user_routeuri: http://localhost:8080predicates:- Path=/user/**

Spring Cloud Gateway的靜態(tài)路由實(shí)現(xiàn)的原理主要通過Reactive模式下的Netty處理方式,以及Project Reactor中的Flux和Mono模型來處理并發(fā)請求。此外,它還使用了Spring 5的核心Webflux框架進(jìn)行路由分發(fā)。

具體來說,當(dāng)請求到來時(shí),Spring Cloud Gateway會(huì)根據(jù)配置文件中的靜態(tài)路由信息,將請求轉(zhuǎn)發(fā)到相應(yīng)的目標(biāo)地址。

核心的代碼主要集中在RoutePredicateHandlerMapping和FilteringWebHandler類中。

// RoutePredicateHandlerMapping用于處理請求的映射關(guān)系
public class RoutePredicateHandlerMapping extends AbstractHandlerMapping {public RoutePredicateHandlerMapping(GatewayProperties properties, RouteLocator routeLocator, ProxyExchangeArgumentResolver proxyExchangeArgumentResolver, ServerCodecConfigurer serverCodecConfigurer, Environment environment) {...}...
}// FilteringWebHandler用于處理各種過濾器
public class FilteringWebHandler implements WebHandler {private final List<GlobalFilter> globalFilters;public FilteringWebHandler(List<GlobalFilter> globalFilters) {this.globalFilters = globalFilters;}...
}

實(shí)際上,配置靜態(tài)路由的主要工作量在于編寫配置文件和理解路由斷言,Spring Cloud Gateway已經(jīng)為處理了復(fù)雜的路由轉(zhuǎn)發(fā)和過濾器操作。

具體的路由匹配和轉(zhuǎn)發(fā)過程則由Spring Cloud Gateway框架自動(dòng)處理。在處理請求時(shí),Gateway會(huì)依次經(jīng)過負(fù)載均衡器、過濾器鏈和路由斷言的處理,并最終將請求轉(zhuǎn)發(fā)到配置的目標(biāo)地址。

2. 動(dòng)態(tài)路由

動(dòng)態(tài)路由通??梢岳斫鉃閮煞N方式,一種通過外部配置存儲(chǔ)動(dòng)態(tài)更新網(wǎng)關(guān)路由,另一種是通過API 的方式動(dòng)態(tài)新增修改刪除網(wǎng)關(guān)路由。

1. 利用外部存儲(chǔ)

動(dòng)態(tài)路由與靜態(tài)路由的主要區(qū)別在于,動(dòng)態(tài)路由允許在運(yùn)行時(shí)更新路由配置,而不需要重啟應(yīng)用。Spring Cloud Gateway支持通過配置中心(如Spring Cloud Config)。

實(shí)現(xiàn)動(dòng)態(tài)路由的原理主要是通過監(jiān)聽配置中心的變化,當(dāng)配置發(fā)生變化時(shí),使用Event機(jī)制觸發(fā)路由信息的更新。Spring Cloud Gateway會(huì)自動(dòng)處理新的路由配置并更新其內(nèi)部的路由表。

核心代碼主要集中在以下幾個(gè)類中:
當(dāng)配置中心發(fā)生更改時(shí),RouteRefreshListener會(huì)監(jiān)聽到相關(guān)事件,觸發(fā)RefreshRoutesEvent事件,從而使CachingRouteLocator更新路由信息。這樣,Spring Cloud Gateway就可以在運(yùn)行時(shí)動(dòng)態(tài)地處理新的路由配置。

  1. CachingRouteLocator:它負(fù)責(zé)緩存和管理路由信息,同時(shí)也會(huì)處理路由信息的更新。
public abstract class CachingRouteLocator implements RouteLocator, ApplicationListener<RefreshRoutesEvent> {public abstract Flux<Route> fetch();@Overridepublic void onApplicationEvent(RefreshRoutesEvent event) {// 當(dāng)收到一個(gè)RefreshRoutesEvent事件時(shí),將會(huì)觸發(fā)路由信息的更新this.resetRoutes().subscribe();}...
}
  1. RouteDefinitionRouteLocator:它繼承自CachingRouteLocator,并負(fù)責(zé)從RouteDefinitionLocator中獲取路由定義,然后根據(jù)路由定義創(chuàng)建路由。
public class RouteDefinitionRouteLocator extends CachingRouteLocator {public RouteDefinitionRouteLocator(RouteDefinitionLocator routeDefinitionLocator, List<GatewayFilterFactory> gatewayFilters, List<RoutePredicateFactory> routePredicates, RouteDefinitionHandlerFilter routeDefinitionHandlerFilter, ConfigurationService configurationService, GatewayProperties properties) {...}...
}
  1. RouteRefreshListener:它負(fù)責(zé)監(jiān)聽配置中心的變化,并在檢測到更改時(shí)發(fā)布一個(gè)RefreshRoutesEvent事件。
@Configuration
public class RouteRefreshListener {@Beanpublic ApplicationListener<?> routeChangeListener(RouteDefinitionRouteLocator routeDefinitionRouteLocator) {return new ApplicationListener<RefreshRoutesResultEvent>() {@Overridepublic void onApplicationEvent(RefreshRoutesResultEvent event) {routeDefinitionRouteLocator.onApplicationEvent(new RefreshRoutesEvent(this));}};}
}

要實(shí)現(xiàn)動(dòng)態(tài)路由,還需要在配置文件中配置相應(yīng)的配置中心,例如使用Spring Cloud Config:

spring:cloud:gateway:discovery:locator:enabled: trueroutes:- id: dynamic_routeuri: lb://service-idpredicates:- Path=/dynamic_path/**config:uri: http://config-server-urilabel: mastername: gateway

2. API動(dòng)態(tài)路由

在Spring Cloud Gateway運(yùn)行時(shí),通過調(diào)用API動(dòng)態(tài)創(chuàng)建和修改的路由規(guī)則。這種路由規(guī)則可以根據(jù)需要進(jìn)行實(shí)時(shí)的修改。動(dòng)態(tài)路由通常需要通過編程方式創(chuàng)建。

在Spring Cloud Gateway中,可以通過調(diào)用Gateway API來動(dòng)態(tài)地創(chuàng)建和修改路由規(guī)則。這些路由規(guī)則可以在運(yùn)行時(shí)進(jìn)行實(shí)時(shí)修改。要實(shí)現(xiàn)這一功能,需要使用RouteDefinitionWriter接口,它提供了添加、刪除和更新路由定義的方法。

Spring Cloud Gateway中動(dòng)態(tài)地創(chuàng)建和修改路由規(guī)則

依賴

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

創(chuàng)建一個(gè)RouteController來處理動(dòng)態(tài)路由的創(chuàng)建、更新和刪除操作

@RestController
@RequestMapping("/route")
public class RouteController {@Autowiredprivate RouteDefinitionWriter routeDefinitionWriter;@Autowiredprivate RouteDefinitionLocator routeDefinitionLocator;@PostMappingpublic Mono<Void> add(@RequestBody RouteDefinition routeDefinition) {return routeDefinitionWriter.save(Mono.just(routeDefinition)).then();}@PutMappingpublic Mono<Void> update(@RequestBody RouteDefinition routeDefinition) {return routeDefinitionWriter.delete(Mono.just(routeDefinition.getId())).then(routeDefinitionWriter.save(Mono.just(routeDefinition))).then();}@DeleteMapping("/{id}")public Mono<Void> delete(@PathVariable String id) {return routeDefinitionWriter.delete(Mono.just(id));}@GetMappingpublic Flux<RouteDefinition> getRoutes() {return routeDefinitionLocator.getRouteDefinitions();}
}

在這個(gè)例子中,使用RouteDefinitionWriter保存、更新和刪除路由定義。當(dāng)定義新的路由規(guī)則或者更新現(xiàn)有的路由規(guī)則時(shí),會(huì)自動(dòng)觸發(fā)路由表的刷新。

現(xiàn)在就可以使用HTTP API來動(dòng)態(tài)地創(chuàng)建、修改和刪除路由規(guī)則了:

  1. 添加一個(gè)新的路由規(guī)則:

    POST /route
    {"id": "my_route","uri": "http://example.com","predicates": [{"name": "Path","args": {"pattern": "/mypath/**"}}],"filters": [{"name": "RewritePath","args": {"regexp": "/mypath/(?<segment>.*)","replacement": "/${segment}"}}]
    }
    
  2. 更新現(xiàn)有的路由規(guī)則:

    PUT /route
    {"id": "my_route","uri": "http://example.com","predicates": [{"name": "Path","args": {"pattern": "/mypath_v2/**"}}],"filters": [{"name": "RewritePath","args": {"regexp": "/mypath_v2/(?<segment>.*)","replacement": "/${segment}"}}]
    }
    
  3. 刪除現(xiàn)有的路由規(guī)則:

    DELETE /route/my_route
    

通過這種方法,可以在Spring Cloud Gateway運(yùn)行時(shí)動(dòng)態(tài)地創(chuàng)建和修改路由規(guī)則,以滿足不斷變化的業(yè)務(wù)需求。

3. 服務(wù)發(fā)現(xiàn)路由(自動(dòng)路由)

3.1. 配置方式

這是一種特殊的動(dòng)態(tài)路由,其路由規(guī)則是根據(jù)服務(wù)發(fā)現(xiàn)機(jī)制來自動(dòng)創(chuàng)建的。
在微服務(wù)架構(gòu)中,服務(wù)發(fā)現(xiàn)是一種特別重要的機(jī)制,它讓微服務(wù)能夠自動(dòng)地發(fā)現(xiàn)網(wǎng)絡(luò)中的其他服務(wù),并知道如何與它們進(jìn)行交互。Spring Cloud Gateway通過與服務(wù)注冊中心(如Eureka、Consul等)集成,實(shí)現(xiàn)了自動(dòng)的服務(wù)發(fā)現(xiàn)路由功能。

當(dāng)一個(gè)新的服務(wù)實(shí)例被注冊到服務(wù)注冊中心時(shí),Spring Cloud Gateway會(huì)自動(dòng)發(fā)現(xiàn)它,并創(chuàng)建一個(gè)新的路由規(guī)則,將請求轉(zhuǎn)發(fā)到這個(gè)服務(wù)。同樣,當(dāng)一個(gè)服務(wù)實(shí)例下線或被注銷時(shí),對應(yīng)的路由規(guī)則也會(huì)被自動(dòng)刪除,這就是所謂的服務(wù)發(fā)現(xiàn)路由或者自動(dòng)路由。

這種機(jī)制可以極大地簡化服務(wù)間的交互,因?yàn)椴恍枰謩?dòng)地為每一個(gè)服務(wù)定義路由規(guī)則。

在Spring Cloud Gateway中使用服務(wù)發(fā)現(xiàn)的一個(gè)簡單示例

添加 Spring Cloud Gateway和 Eureka的依賴:

<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>

application.yml文件中配置Eureka和Gateway:

spring:cloud:gateway:discovery:locator:enabled: true # 啟用服務(wù)發(fā)現(xiàn)路由application:name: gateway-service
eureka:client:service-url:defaultZone: http://localhost:8761/eureka/

啟動(dòng)Eureka Server和的服務(wù),然后啟動(dòng)Spring Cloud Gateway,Gateway就會(huì)自動(dòng)發(fā)現(xiàn)注冊在Eureka中的服務(wù),并為它們創(chuàng)建路由規(guī)則。例如有一個(gè)名為user-service的服務(wù),那么就可以通過http://localhost:8080/user-service來訪問。

3.2 自動(dòng)路由(服務(wù)發(fā)現(xiàn))原理

在Spring Cloud Gateway中實(shí)現(xiàn)服務(wù)發(fā)現(xiàn)路由的核心類是DiscoveryClientRouteDefinitionLocator。這個(gè)類負(fù)責(zé)從注冊中心獲取服務(wù)實(shí)例信息,并基于這些信息創(chuàng)建路由定義。當(dāng)服務(wù)實(shí)例發(fā)生變化時(shí),DiscoveryClientRouteDefinitionLocator會(huì)自動(dòng)更新路由定義。

服務(wù)發(fā)現(xiàn)路由的底層原理主要包括以下幾個(gè)方面:

  1. 集成服務(wù)發(fā)現(xiàn)組件:Spring Cloud Gateway可以與多種服務(wù)注冊中心(如Eureka、Consul等)集成。這些集成是通過實(shí)現(xiàn)DiscoveryClient接口來完成的。DiscoveryClient提供了獲取服務(wù)實(shí)例信息的方法,例如getInstances(String serviceId)。這使得Gateway可以獲取到注冊中心中所有服務(wù)的實(shí)例信息。

  2. 創(chuàng)建路由定義:DiscoveryClientRouteDefinitionLocator會(huì)將從DiscoveryClient獲取到的服務(wù)實(shí)例信息轉(zhuǎn)換為RouteDefinition對象。這些RouteDefinition對象包含了路由的基本信息,如ID、URI、斷言和過濾器等。通過這些信息,Gateway可以知道如何將請求路由到特定的服務(wù)實(shí)例。

  3. 路由規(guī)則更新:當(dāng)注冊中心中的服務(wù)實(shí)例發(fā)生變化時(shí),DiscoveryClientRouteDefinitionLocator會(huì)自動(dòng)更新路由規(guī)則。這是通過監(jiān)聽服務(wù)實(shí)例變化事件來實(shí)現(xiàn)的。當(dāng)接收到服務(wù)實(shí)例變化事件后,DiscoveryClientRouteDefinitionLocator會(huì)重新獲取服務(wù)實(shí)例信息,并更新RouteDefinition對象。這樣,Gateway就能實(shí)時(shí)地感知到服務(wù)實(shí)例的變化,并相應(yīng)地調(diào)整路由規(guī)則。

  4. 請求轉(zhuǎn)發(fā):當(dāng)Gateway接收到一個(gè)請求時(shí),它會(huì)根據(jù)DiscoveryClientRouteDefinitionLocator提供的路由定義匹配相應(yīng)的路由規(guī)則。然后,Gateway會(huì)將請求轉(zhuǎn)發(fā)到匹配的服務(wù)實(shí)例。這個(gè)轉(zhuǎn)發(fā)過程是通過NettyRoutingFilter完成的,它會(huì)根據(jù)RouteDefinition中的URI信息轉(zhuǎn)發(fā)請求。

核心源碼
GatewayDiscoveryClientAutoConfiguration

我們可以看到 當(dāng) DiscoveryClient 存在并且 spring.cloud.gateway.discovery.locator.enabledtrue 時(shí),創(chuàng)建一個(gè) DiscoveryClientRouteDefinitionLocator Bean,允許 Spring Cloud Gateway 動(dòng)態(tài)地從服務(wù)注冊中心發(fā)現(xiàn)路由定義。
在這里插入圖片描述

DiscoveryClientRouteDefinitionLocator核心方法getRouteDefinitions

getRouteDefinitions方法的主要目的是從 DiscoveryClient 獲取服務(wù)實(shí)例信息并將其轉(zhuǎn)換為路由定義。首先解析 includeExpressionurlExpression,然后根據(jù) includeExpression 創(chuàng)建一個(gè)用于判斷服務(wù)實(shí)例是否需要被包含在路由定義中的 Predicate。接著從 DiscoveryClient 獲取所有服務(wù)實(shí)例信息,并轉(zhuǎn)換為 RouteDefinition。轉(zhuǎn)換過程中會(huì)生成 PredicateDefinitionFilterDefinition。最后返回一個(gè)包含所有路由定義的 Flux 對象。

@Override
public Flux<RouteDefinition> getRouteDefinitions() {// 創(chuàng)建一個(gè) SpelExpressionParser 用于解析表達(dá)式SpelExpressionParser parser = new SpelExpressionParser();// 解析 includeExpression,用于判斷服務(wù)實(shí)例是否需要被包含在路由定義中Expression includeExpr = parser.parseExpression(properties.getIncludeExpression());// 解析 urlExpression,用于生成服務(wù)實(shí)例對應(yīng)的 URIExpression urlExpr = parser.parseExpression(properties.getUrlExpression());// 根據(jù) includeExpression 創(chuàng)建一個(gè) Predicate,用于判斷服務(wù)實(shí)例是否需要被包含在路由定義中Predicate<ServiceInstance> includePredicate;if (properties.getIncludeExpression() == null || "true".equalsIgnoreCase(properties.getIncludeExpression())) {includePredicate = instance -> true;} else {includePredicate = instance -> {Boolean include = includeExpr.getValue(evalCtxt, instance, Boolean.class);if (include == null) {return false;}return include;};}// 從 DiscoveryClient 獲取所有服務(wù)實(shí)例信息并轉(zhuǎn)換為路由定義return Flux.fromIterable(discoveryClient.getServices()).map(discoveryClient::getInstances) // 獲取每個(gè)服務(wù)的所有實(shí)例.filter(instances -> !instances.isEmpty()) // 過濾掉沒有實(shí)例的服務(wù).map(instances -> instances.get(0)) // 獲取每個(gè)服務(wù)的第一個(gè)實(shí)例.filter(includePredicate) // 過濾掉不需要被包含在路由定義中的服務(wù)實(shí)例.map(instance -> { // 將服務(wù)實(shí)例轉(zhuǎn)換為 RouteDefinitionString serviceId = instance.getServiceId();RouteDefinition routeDefinition = new RouteDefinition();routeDefinition.setId(this.routeIdPrefix + serviceId);// 獲取服務(wù)實(shí)例對應(yīng)的 URIString uri = urlExpr.getValue(evalCtxt, instance, String.class);routeDefinition.setUri(URI.create(uri));final ServiceInstance instanceForEval = new DelegatingServiceInstance(instance, properties);// 生成 PredicateDefinitionfor (PredicateDefinition original : this.properties.getPredicates()) {PredicateDefinition predicate = new PredicateDefinition();predicate.setName(original.getName());for (Map.Entry<String, String> entry : original.getArgs().entrySet()) {String value = getValueFromExpr(evalCtxt, parser, instanceForEval, entry);predicate.addArg(entry.getKey(), value);}routeDefinition.getPredicates().add(predicate);}// 生成 FilterDefinitionfor (FilterDefinition original : this.properties.getFilters()) {FilterDefinition filter = new FilterDefinition();filter.setName(original.getName());for (Map.Entry<String, String> entry : original.getArgs().entrySet()) {String value = getValueFromExpr(evalCtxt, parser, instanceForEval, entry);filter.addArg(entry.getKey(), value);}routeDefinition.getFilters().add(filter);}return routeDefinition;});
}

4. Gateway路由的核心組件

4.1 路由斷言

路由斷言(Route Predicates)是Spring Cloud Gateway中的一個(gè)核心概念,它負(fù)責(zé)匹配HTTP請求的屬性,并決定是否將請求路由到特定的服務(wù)。

使用斷言,可以基于許多不同的請求屬性定義路由規(guī)則,包括:

  • 請求路徑:比如請求的URL。
  • 請求方法:GET、POST等。
  • 請求頭:可以匹配特定的請求頭字段和值。
  • 查詢參數(shù):可以匹配URL的查詢參數(shù)。
  • Cookie:可以匹配特定的cookie

斷言的定義通常在Spring配置文件(如application.yaml)中,作為路由定義的一部分。每個(gè)斷言都是一種謂詞(Predicate),這是一個(gè)返回true或false的函數(shù)。

路由斷言的示例:

spring:cloud:gateway:routes:- id: user_serviceuri: http://localhost:8080/userpredicates:- Path=/user/**- Method=GET- Header=X-Request-User, \d+

在這個(gè)例子中,定義了一個(gè)名為"user_service"的路由,其目標(biāo)URI為"http://localhost:8080/user"。定義了三個(gè)斷言:

  1. Path斷言:只有當(dāng)請求路徑以"/user/"開頭時(shí),才會(huì)觸發(fā)該路由。
  2. Method斷言:只有當(dāng)HTTP請求方法為GET時(shí),才會(huì)觸發(fā)該路由。
  3. Header斷言:只有當(dāng)請求頭中存在名為"X-Request-User"的字段,并且其值為數(shù)字時(shí),才會(huì)觸發(fā)該路由。

只有當(dāng)所有的斷言都返回true時(shí),該請求才會(huì)被路由到目標(biāo)服務(wù)。否則,Spring Cloud Gateway將返回404錯(cuò)誤。

組合并生效相當(dāng)于并且的關(guān)系

在這個(gè)示例中,只有滿足以下所有條件的請求才會(huì)路由到http://localhost:8080/:

  • 請求路徑以/api/開頭
  • 請求方法為GET
  • 請求頭中包含X-Request-Id,且其值為數(shù)字
  • 查詢參數(shù)中包含debug,并且其值為true
  • Cookie中包含sessionId,并且其值不為空
spring:cloud:gateway:routes:- id: host_routeuri: http://localhost:8080/predicates:- Path=/api/**- Method=GET- Header=X-Request-Id, \d+- Query=debug, true- Cookie=sessionId, .+

如果要或的關(guān)系需要分配多個(gè)路由

如果想要以"或"的關(guān)系生效,需要定義多個(gè)路由??紤]到Spring Cloud Gateway的工作方式,一個(gè)請求只能被一個(gè)路由處理。這意味著謂詞是以"與"的方式工作的,而不是"或"。如果想要一個(gè)請求被多個(gè)謂詞處理,需要?jiǎng)?chuàng)建多個(gè)路由。每個(gè)路由有一個(gè)謂詞,這樣一個(gè)請求可以匹配多個(gè)路由。

在以下的配置中,如果請求路徑以/api/開頭, 或請求方法為GET, 或請求頭中包含X-Request-Id且其值為數(shù)字, 或查詢參數(shù)中包含debug且其值為true, 或Cookie中包含sessionId且其值不為空,任何一個(gè)條件滿足,請求都會(huì)路由到http://localhost:8080/。

spring:cloud:gateway:routes:- id: host_route1uri: http://localhost:8080/predicates:- Path=/api/**- id: host_route2uri: http://localhost:8080/predicates:- Method=GET- id: host_route3uri: http://localhost:8080/predicates:- Header=X-Request-Id, \d+- id: host_route4uri: http://localhost:8080/predicates:- Query=debug, true- id: host_route5uri: http://localhost:8080/predicates:- Cookie=sessionId, .+

4.2 路由過濾器

Spring Cloud Gateway作為一個(gè)API網(wǎng)關(guān),提供了很多功能,如路由轉(zhuǎn)發(fā)、斷路器、限流等。其中,路由過濾器是其核心功能之一,它允許我們在請求被路由之前或之后對請求進(jìn)行處理。本文將詳細(xì)介紹Spring Cloud Gateway的路由過濾器。

路由過濾器概念

路由過濾器是一個(gè)Java類,用于修改進(jìn)入或退出網(wǎng)關(guān)的HTTP請求和響應(yīng)。它包含兩種類型的過濾器:

  1. Global Filter:全局過濾器,對所有路由請求生效。
  2. GatewayFilter:網(wǎng)關(guān)過濾器,只對特定路由請求生效。

Spring Cloud Gateway中的過濾器基于WebFilter接口實(shí)現(xiàn),并且實(shí)現(xiàn)了Ordered接口來控制過濾器的執(zhí)行順序。過濾器可以在請求被路由之前(Pre過濾器)或之后(Post過濾器)進(jìn)行處理。

路由過濾器工廠

Spring Cloud Gateway的過濾器是通過工廠創(chuàng)建的。這些工廠實(shí)現(xiàn)了GatewayFilterFactory接口,這個(gè)接口包含兩個(gè)方法:

  • apply(T config):將配置信息傳遞給過濾器,并創(chuàng)建過濾器實(shí)例。
  • getConfigClass():返回過濾器所使用的配置類。

內(nèi)置路由過濾器

Spring Cloud Gateway提供了許多內(nèi)置過濾器,可以覆蓋大部分基本功能。以下是一些常用的內(nèi)置過濾器:

  1. AddRequestHeader:添加請求頭。
  2. AddRequestParameter:添加請求參數(shù)。
  3. AddResponseHeader:添加響應(yīng)頭。
  4. PrefixPath:添加前綴路徑。
  5. RewritePath:重寫請求路徑。
  6. Retry:重試。
  7. SetPath:設(shè)置請求路徑。
  8. SetResponseHeader:設(shè)置響應(yīng)頭。
  9. StripPrefix:去掉前綴。
  10. Hystrix:使用Hystrix斷路器。

自定義路由過濾器

除了內(nèi)置過濾器以外,我們還可以自定義過濾器。自定義過濾器需要實(shí)現(xiàn)GatewayFilter接口,并重寫filter(ServerWebExchange exchange, GatewayFilterChain chain)方法。下面是一個(gè)簡單的自定義過濾器示例:
創(chuàng)建了一個(gè)名為 CustomGatewayFilterFactory 的類,實(shí)現(xiàn)了 GatewayFilterFactory<GatewayFilterFactory.Args> 接口,并重寫了 applyname 方法。在 apply 方法中,我們返回一個(gè)新的 CustomGatewayFilter 實(shí)例。在 name 方法中,我們返回過濾器的名稱,這個(gè)名稱需要與配置文件中的 filters 部分所引用的名稱相匹配。最后,我們將 CustomGatewayFilterFactory 注冊為一個(gè) Bean。

public class CustomGatewayFilter implements GatewayFilter {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {// 在請求被路由之前執(zhí)行的邏輯System.out.println("Custom Gateway Filter Pre");return chain.filter(exchange).then(Mono.fromRunnable(() -> {// 在請求被路由之后執(zhí)行的邏輯System.out.println("Custom Gateway Filter Post");}));}
}

要在配置文件中為特定路由配置 CustomGatewayFilter,需要在 Spring Cloud Gateway 的配置文件(如 application.ymlapplication.properties)中定義路由規(guī)則,并在 filters 部分引用的 CustomGatewayFilter。以下是一個(gè)在 application.yml 中配置 CustomGatewayFilter 的示例:

spring:cloud:gateway:routes:- id: my_routeuri: http://example.com # 目標(biāo)服務(wù)的地址predicates:- Path=/my_path/** # 路由條件,例如路徑匹配filters:- name: CustomFilter # 在這里引用的自定義過濾器

需要先將 CustomGatewayFilter 注冊為一個(gè)全局過濾器。為了達(dá)到這個(gè)目的,需要?jiǎng)?chuàng)建一個(gè) GatewayFilterFactory,并將其注冊為一個(gè) Bean。請參考以下示例:

@Configuration
public class CustomGatewayFilterConfiguration {@Beanpublic CustomGatewayFilterFactory customGatewayFilterFactory() {return new CustomGatewayFilterFactory();}public static class CustomGatewayFilterFactory implements GatewayFilterFactory<GatewayFilterFactory.Args> {@Overridepublic GatewayFilter apply(GatewayFilterFactory.Args args) {return new CustomGatewayFilter();}@Overridepublic String name() {return "CustomFilter";}}
}

5. 路由的動(dòng)態(tài)刷新

我們寫一個(gè)簡化的教程來看下如何在Spring Cloud Gateway中實(shí)現(xiàn)動(dòng)態(tài)路由刷新。

5.1. 添加依賴

在Gateway服務(wù)的pom.xml文件中添加以下依賴:

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

這里我們使用RabbitMQ作為消息代理,如果想使用其他消息代理,請?zhí)鎿Q相應(yīng)的依賴。

5.2. 配置application.yml

在Gateway服務(wù)的src/main/resources/application.yml中添加以下配置:

spring:cloud:gateway:discovery:locator:enabled: trueroutes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user-service/**config:uri: http://localhost:8888rabbitmq:host: localhostport: 5672username: guestpassword: guestbus:id: ${spring.application.name}:${server.port}

這里我們配置了一個(gè)名為user-service的路由,路由的配置信息將從Config Server(地址為http://localhost:8888)獲取。

5.3. 創(chuàng)建Config Server

創(chuàng)建一個(gè)新的Spring Boot項(xiàng)目,名為config-server。在pom.xml文件中添加以下依賴:

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-server</artifactId>
</dependency>

src/main/resources/application.yml中添加以下配置:

server:port: 8888
spring:cloud:config:server:git:uri: https://github.com/your-username/your-repo.git

這里配置了Config Server從遠(yuǎn)程Git倉庫獲取配置信息。

src/main/java/com/example/configserver/ConfigServerApplication.java中添加@EnableConfigServer注解以啟動(dòng)Config Server:

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {public static void main(String[] args) {SpringApplication.run(ConfigServerApplication.class, args);}
}

啟動(dòng)Config Server。

5.4. 在遠(yuǎn)程Git倉庫中添加配置文件

在的遠(yuǎn)程Git倉庫中添加一個(gè)名為gateway-service.yml的文件,內(nèi)容如下:

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user-service/**

這里配置了一個(gè)名為user-service的路由。

5.5. 啟動(dòng)Gateway服務(wù)

現(xiàn)在啟動(dòng)的Gateway服務(wù),它將從Config Server獲取最新的路由信息。可以通過訪問http://localhost:8080/user-service/some-api來測試路由是否生效。

5.6. 動(dòng)態(tài)刷新路由信息

當(dāng)gateway-service.yml文件發(fā)生變化并推送到遠(yuǎn)程Git倉庫后,可以發(fā)送一個(gè)POST請求到http://localhost:8080/actuator/refresh端點(diǎn)以刷新Gateway的路由信息。

也可以在config-server項(xiàng)目中添加Spring Cloud Bus的依賴,并添加相應(yīng)的配置,以實(shí)現(xiàn)自動(dòng)廣播路由變更消息。

6. 處理路由失敗和異常

如何處理路由失敗和異常也是大家在寫一個(gè)高可用,健壯性良好的網(wǎng)關(guān)服務(wù)的基本要求。那么在本教程中,我們來了解一下Spring Cloud Gateway中如何處理路由失敗和異常,以及如何配置回退和重試策略。

6.1 處理請求失敗和異常

當(dāng)路由轉(zhuǎn)發(fā)過程中發(fā)生異常,例如目標(biāo)服務(wù)不可用,可以使用Gateway的全局異常處理器來捕獲異常并返回一個(gè)友好的錯(cuò)誤響應(yīng)。默認(rèn)情況下,Gateway會(huì)使用org.springframework.cloud.gateway.handler.GlobalErrorWebExceptionHandler作為全局異常處理器??梢酝ㄟ^實(shí)現(xiàn)ErrorWebExceptionHandler接口并注冊為Spring Bean來自定義全局異常處理器。
寫一個(gè)簡單的例子可供參考
自定義CustomGlobalExceptionHandler繼承了AbstractErrorWebExceptionHandler并覆蓋了getRoutingFunction方法,以自定義錯(cuò)誤響應(yīng)。

@Component
public class CustomGlobalExceptionHandler extends AbstractErrorWebExceptionHandler {public CustomGlobalExceptionHandler(ErrorAttributes errorAttributes,WebProperties.Resources resources,ApplicationContext applicationContext,ServerCodecConfigurer serverCodecConfigurer) {super(errorAttributes, resources, applicationContext);setMessageWriters(serverCodecConfigurer.getWriters());setMessageReaders(serverCodecConfigurer.getReaders());}@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {Throwable error = getError(request);// 自定義響應(yīng)體Map<String, Object> errorAttributes = new HashMap<>();errorAttributes.put("message", error.getMessage());errorAttributes.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());errorAttributes.put("timestamp", LocalDateTime.now());return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(errorAttributes));}
}

默認(rèn)實(shí)現(xiàn)是DefaultErrorWebExceptionHandler
在這里插入圖片描述

6.2 配置回退和重試策略

使用Spring Cloud Gateway,可以為路由配置回退和重試策略。回退策略允許在轉(zhuǎn)發(fā)請求失敗時(shí)返回一個(gè)預(yù)定義的響應(yīng)。重試策略允許在請求失敗時(shí)嘗試重新發(fā)送請求。

為了配置回退策略,可以在路由配置中添加fallbackUri屬性。

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user-service/**filters:- name: Hystrixargs:name: user-servicefallbackUri: forward:/fallback

user-service路由配置了一個(gè)回退URI,它會(huì)將請求轉(zhuǎn)發(fā)到/fallback端點(diǎn)。需要在的Gateway服務(wù)中實(shí)現(xiàn)這個(gè)端點(diǎn),并返回一個(gè)預(yù)定義的響應(yīng)。

為了配置重試策略,可以在路由配置中添加Retry過濾器。
user-service路由配置了一個(gè)重試策略。當(dāng)請求方法為GET且服務(wù)器返回500 Internal Server Error狀態(tài)時(shí),Gateway會(huì)嘗試重新發(fā)送請求,最多重試3次。

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user-service/**filters:- name: Retryargs:retries: 3statuses: INTERNAL_SERVER_ERRORmethods: GET

7. 高級路由功能

寫不動(dòng)了,路由詳解就到這兒,后面有時(shí)間補(bǔ)充一下高級路由功能。

  • 7.1 如何配置負(fù)載均衡
  • 7.2 如何配置熔斷器
  • 7.3 如何配置速率限制

8. 參考文檔

Spring Cloud Gateway官方文檔 https://cloud.spring.io/spring-cloud-gateway/2.0.x/single/spring-cloud-gateway.html
在這里插入圖片描述

http://www.risenshineclean.com/news/41017.html

相關(guān)文章:

  • 2018網(wǎng)站的建設(shè)與維護(hù)前景網(wǎng)店代運(yùn)營商
  • 鎮(zhèn)江做網(wǎng)站的做網(wǎng)站用什么編程軟件
  • 科技網(wǎng)站 網(wǎng)站建設(shè)廣告公司業(yè)務(wù)推廣
  • 網(wǎng)站開發(fā)需解決什么問題廣州百度關(guān)鍵詞搜索
  • 用html做班級網(wǎng)站萬網(wǎng)域名注冊信息查詢
  • 有道翻譯網(wǎng)站 做翻譯太原網(wǎng)站推廣排名
  • c做網(wǎng)站百度云登錄
  • wordpress首頁加登錄在線seo短視頻
  • 免費(fèi)學(xué)校網(wǎng)站管理系統(tǒng)南京百度seo排名
  • 有哪些做婚禮電子請柬的網(wǎng)站品牌推廣活動(dòng)策劃方案
  • 榆林免費(fèi)做網(wǎng)站推廣引流渠道
  • 如何做分類網(wǎng)站信息營銷市場調(diào)研一般怎么做
  • 惠州做網(wǎng)站 百度優(yōu)化線上宣傳渠道和宣傳方式
  • 達(dá)州網(wǎng)站建設(shè)公司電商引流推廣方法
  • wordpress 子目錄 404西安seo優(yōu)化公司
  • 網(wǎng)上建立網(wǎng)站網(wǎng)絡(luò)營銷策略分析方法
  • 網(wǎng)站解析什么意思建網(wǎng)站需要多少錢和什么條件
  • 網(wǎng)站名怎么寫整站優(yōu)化報(bào)價(jià)
  • 做機(jī)械的網(wǎng)站網(wǎng)站人多怎么優(yōu)化
  • 做汽車團(tuán)購的網(wǎng)站建設(shè)直通車推廣計(jì)劃方案
  • 網(wǎng)頁制作與網(wǎng)站開發(fā)用的軟件友情鏈接的作用大不大
  • 湖北網(wǎng)站建設(shè)公司今天重大新聞事件
  • 會(huì)議網(wǎng)站建設(shè)方案模板搜一搜站長工具
  • 企業(yè)做網(wǎng)站和宣傳冊的作用bt磁力在線種子搜索神器
  • 如何接做網(wǎng)站編程的生意成長電影在線觀看免費(fèi)
  • 網(wǎng)站后臺(tái)管理系統(tǒng)使用百度seo如何快速排名
  • 臨沂網(wǎng)站建設(shè)培訓(xùn)班seo工具優(yōu)化軟件
  • 織夢通用seo網(wǎng)站模板百度客服電話24小時(shí)
  • 企業(yè)網(wǎng)站建設(shè)市場報(bào)價(jià)技術(shù)培訓(xùn)機(jī)構(gòu)排名前十
  • 做百度推廣需要網(wǎng)站嗎快手推廣網(wǎng)站