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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

api网关揭秘--spring cloud gateway源码解析

發(fā)布時(shí)間:2025/4/5 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 api网关揭秘--spring cloud gateway源码解析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

要想了解spring cloud gateway的源碼,要熟悉spring webflux,我的上篇文章介紹了spring webflux。

1.gateway 和zuul對(duì)比

I am the author of spring cloud gateway. Zuul is built on servlet 2.5 (works with 3.x), using blocking APIs. It doesn't support any long lived connections, like websockets. Gateway is built on Spring Framework 5, Project Reactor and Spring Boot 2 using non-blocking APIs. Websockets are supported and it's a much better developer experience since it's tightly integrated with Spring.

簡(jiǎn)單的來(lái)說(shuō):

  1.zuul是基于servlet 2.5,兼容servlet3.0,使用的是阻塞API,不支持長(zhǎng)連接如websocket

  2.Gateway基于spring5,Reactor和Spring boot2使用了非阻塞API,支持websocket,和spring完美集成,對(duì)開(kāi)發(fā)者友好。

  另外

  3.zuul2支持非阻塞API,但沒(méi)有和spring cloud集成,且已經(jīng)停止維護(hù),不在考慮之列。

2.架構(gòu)圖

3.自動(dòng)配置解析core spring.factories

# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration,\ org.springframework.cloud.gateway.config.GatewayAutoConfiguration,\ org.springframework.cloud.gateway.config.GatewayLoadBalancerClientAutoConfiguration,\ org.springframework.cloud.gateway.config.GatewayNoLoadBalancerClientAutoConfiguration,\ org.springframework.cloud.gateway.config.GatewayMetricsAutoConfiguration,\ org.springframework.cloud.gateway.config.GatewayRedisAutoConfiguration,\ org.springframework.cloud.gateway.discovery.GatewayDiscoveryClientAutoConfiguration org.springframework.boot.env.EnvironmentPostProcessor=\ org.springframework.cloud.gateway.config.GatewayEnvironmentPostProcessor

3.1?GatewayClassPathWarningAutoConfiguration檢查前端控制器

@Configuration@ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet")protected static class SpringMvcFoundOnClasspathConfiguration {public SpringMvcFoundOnClasspathConfiguration() {log.warn(BORDER+ "Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. "+ "Please remove spring-boot-starter-web dependency." + BORDER);}}@Configuration@ConditionalOnMissingClass("org.springframework.web.reactive.DispatcherHandler")protected static class WebfluxMissingFromClasspathConfiguration {public WebfluxMissingFromClasspathConfiguration() {log.warn(BORDER + "Spring Webflux is missing from the classpath, "+ "which is required for Spring Cloud Gateway at this time. "+ "Please add spring-boot-starter-webflux dependency." + BORDER);}}

1.若存在springmvc的前端控制器org.springframework.web.servlet.DispatcherServlet,則報(bào)警,原因是使用非阻塞的API

2.若不存在spring webflux的前端控制器org.springframework.web.reactive.DispatcherHandler,則報(bào)警,原因是需要使用非阻塞的API

3.2 網(wǎng)關(guān)自動(dòng)配置GatewayAutoConfiguration

3.2.1?RoutePredicateHandlerMapping

@Beanpublic RoutePredicateHandlerMapping routePredicateHandlerMapping(FilteringWebHandler webHandler, RouteLocator routeLocator,GlobalCorsProperties globalCorsProperties, Environment environment) {return new RoutePredicateHandlerMapping(webHandler, routeLocator,globalCorsProperties, environment);}

RoutePredicateHandlerMapping繼承自AbstractHandlerMapping,在此步進(jìn)行路徑查找

@Overrideprotected Mono<?> getHandlerInternal(ServerWebExchange exchange) {// don't handle requests on the management port if setif (managmentPort != null&& exchange.getRequest().getURI().getPort() == managmentPort.intValue()) {return Mono.empty();}exchange.getAttributes().put(GATEWAY_HANDLER_MAPPER_ATTR, getSimpleName());return lookupRoute(exchange)// .log("route-predicate-handler-mapping", Level.FINER) //name this.flatMap((Function<Route, Mono<?>>) r -> {exchange.getAttributes().remove(GATEWAY_PREDICATE_ROUTE_ATTR);if (logger.isDebugEnabled()) {logger.debug("Mapping [" + getExchangeDesc(exchange) + "] to " + r);} exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, r); //2return Mono.just(webHandler);}).switchIfEmpty(Mono.empty().then(Mono.fromRunnable(() -> {exchange.getAttributes().remove(GATEWAY_PREDICATE_ROUTE_ATTR);if (logger.isTraceEnabled()) {logger.trace("No RouteDefinition found for ["+ getExchangeDesc(exchange) + "]");}})));}protected Mono<Route> lookupRoute(ServerWebExchange exchange) {//1return this.routeLocator.getRoutes()// individually filter routes so that filterWhen error delaying is not a// problem.concatMap(route -> Mono.just(route).filterWhen(r -> {// add the current route we are testing exchange.getAttributes().put(GATEWAY_PREDICATE_ROUTE_ATTR, r.getId());return r.getPredicate().apply(exchange);})// instead of immediately stopping main flux due to error, log and// swallow it.doOnError(e -> logger.error("Error applying predicate for route: " + route.getId(),e)).onErrorResume(e -> Mono.empty()))// .defaultIfEmpty() put a static Route not found// or .switchIfEmpty()// .switchIfEmpty(Mono.<Route>empty().log("noroute")) .next()// TODO: error handling.map(route -> {if (logger.isDebugEnabled()) {logger.debug("Route matched: " + route.getId());}validateRoute(route, exchange);return route;});/** TODO: trace logging if (logger.isTraceEnabled()) {* logger.trace("RouteDefinition did not match: " + routeDefinition.getId()); }*/}

?1.通過(guò)RouteLocator返回Route

?

?關(guān)于Route的定義

private Route(String id, URI uri, int order,AsyncPredicate<ServerWebExchange> predicate,List<GatewayFilter> gatewayFilters) {this.id = id;this.uri = uri;this.order = order;this.predicate = predicate;this.gatewayFilters = gatewayFilters;}

可以看出url和gatewayFilter進(jìn)行了綁定

?2.將Route放入ServerWebExchange的屬性中。

3.2.2?FilteringWebHandler

@Beanpublic FilteringWebHandler filteringWebHandler(List<GlobalFilter> globalFilters) {return new FilteringWebHandler(globalFilters);}

?

?

參考文獻(xiàn):

【1】https://stackoverflow.com/questions/47092048/how-spring-cloud-gateway-is-different-from-zuul

【2】https://blog.csdn.net/xuejike/article/details/81290695

轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/10402768.html

總結(jié)

以上是生活随笔為你收集整理的api网关揭秘--spring cloud gateway源码解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。