最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringCloud Gateway自動裝配實現(xiàn)流程詳解

 更新時間:2022年10月21日 10:59:30   作者:Polarisy丶  
Spring Cloud Gateway旨在為微服務架構提供一種簡單有效的、統(tǒng)一的 API 路由管理方式。Spring Cloud Gateway 作為 Spring Cloud 生態(tài)系中的網關,它不僅提供統(tǒng)一的路由方式,并且基于 Filter 鏈的方式提供了網關基本的功能,例如:安全、監(jiān)控/埋點和限流等

啟動依賴

找到gateway的依賴,spring-cloud-starter-gateway

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

點進去之后找到它的依賴

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter</artifactId>
      <version>3.1.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gateway-server</artifactId>
      <version>3.1.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
      <version>2.6.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-loadbalancer</artifactId>
      <version>3.1.1</version>
      <scope>compile</scope>
      <optional>true</optional>
    </dependency>
  </dependencies>

從名稱上可以判斷spring-cloud-gateway-server是gateway的核心依賴,找到依賴包,看到如下結構

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.GatewayResilience4JCircuitBreakerAutoConfiguration,\
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.cloud.gateway.config.SimpleUrlHandlerMappingGlobalCorsAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayReactiveOAuth2AutoConfiguration

org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.gateway.config.GatewayEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.cloud.gateway.support.MvcFoundOnClasspathFailureAnalyzer

其中比較重要的是GatewayAutoConfiguration,負責很多bean的初始化,類聲明如下:

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@EnableConfigurationProperties
@AutoConfigureBefore({ HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class })
@AutoConfigureAfter({ GatewayReactiveLoadBalancerClientAutoConfiguration.class,
		GatewayClassPathWarningAutoConfiguration.class })
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {			

@AutoConfigureBefore@AutoConfigureAfter分別是在之前和之后加載

其中HttpHandlerAutoConfigurationWebFluxAutoConfiguration算是比較重要的裝配類

WebFluxAutoConfiguration

先看WebFluxAutoConfiguration,類聲明如下:

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@ConditionalOnMissingBean({ WebFluxConfigurationSupport.class })
@AutoConfigureAfter({ ReactiveWebServerFactoryAutoConfiguration.class, CodecsAutoConfiguration.class,
		ReactiveMultipartAutoConfiguration.class, ValidationAutoConfiguration.class,
		WebSessionIdResolverAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class WebFluxAutoConfiguration {

其中部分代碼如下:

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ WebProperties.class, WebFluxProperties.class })
@Import({ EnableWebFluxConfiguration.class })
@Order(0)
public static class WebFluxConfig implements WebFluxConfigurer {

可以看到通過WebFluxAutoConfiguration 通過 WebFluxConfig 導入了 EnableWebFluxConfiguration

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ WebProperties.class, ServerProperties.class })
public static class EnableWebFluxConfiguration extends DelegatingWebFluxConfiguration {

EnableWebFluxConfiguration繼承于DelegatingWebFluxConfiguration

@Configuration(proxyBeanMethods = false)
public class DelegatingWebFluxConfiguration extends WebFluxConfigurationSupport {

DelegatingWebFluxConfiguration又繼承于WebFluxConfigurationSupport

在WebFluxConfigurationSupport中可以看到很熟悉的東西

@Bean
public DispatcherHandler webHandler() {
    //BeanName為webHandler
	return new DispatcherHandler();
}

有點聯(lián)想到DispatcherSerlvet,類似前端控制器

public class DispatcherHandler implements WebHandler, PreFlightRequestHandler, ApplicationContextAware {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->

可以看到DispatcherHandler實現(xiàn)了WebHandler接口并實現(xiàn)了其中的handle方法

public interface WebHandler {
	/**
	 * Handle the web server exchange.
	 * @param exchange the current server exchange
	 * @return {@code Mono<Void>} to indicate when request handling is complete
	 */
	Mono<Void> handle(ServerWebExchange exchange);
}

可以猜到handle應該就是核心的處理方法,此時又有疑問,該方法什么時候被調用,被誰調用的

官方文檔上提到WebHandler 上面還有一個關鍵的 API HttpHandler

For server request processing there are two levels of support.

HttpHandler: Basic contract for HTTP request handling with non-blocking I/O and Reactive Streams back pressure, along with adapters for Reactor Netty, Undertow, Tomcat, Jetty, and any Servlet 3.1+ container.

WebHandler API: Slightly higher level, general-purpose web API for request handling, on top of which concrete programming models such as annotated controllers and functional endpoints are built.

從上面的英文可以看到 HttpHandler 是比 WebHandler 更加底層的一個 API,也就是說很可能是由 HttpHandler 來調用 WebHandler (請求由下往上),那DispatcherHandler作為 WebHandler 的一個實現(xiàn),也很有可能會被HttpHandler的具體實現(xiàn)所持有。

通過HttpHandler的實現(xiàn)類不難找到HttpWebHandlerAdapter 就是我們要找的,并且持有一個WebHandher 對象,當然也可以通過斷點調試找到。

public class HttpWebHandlerAdapter extends WebHandlerDecorator implements HttpHandler {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->

HttpWebHandlerAdapter繼承于WebHandlerDecorator

public class WebHandlerDecorator implements WebHandler {
	private final WebHandler delegate;
	/**
	 * Return the wrapped delegate.
	 */
	public WebHandler getDelegate() {
		return this.delegate;
	}

可以看到WebHandlerDecorator持有WebHandler對象

總之,我們找到了調用 DispatcherHandher 的地方了,那下一步我們要找 HttpWebHandlerAdapter 是在哪里被裝配的,并且webHandler 是是什么時候被注入的,注入的 webHandler 是否就是 DispatcherHandler?

HttpHandlerAutoConfiguration

前面說過的另外一個裝配類HttpHandlerAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ DispatcherHandler.class, HttpHandler.class })
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnMissingBean(HttpHandler.class)
@AutoConfigureAfter({ WebFluxAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class HttpHandlerAutoConfiguration {
	@Configuration(proxyBeanMethods = false)
	public static class AnnotationConfig {
		private final ApplicationContext applicationContext;
		public AnnotationConfig(ApplicationContext applicationContext) {
			this.applicationContext = applicationContext;
		}
		@Bean
		public HttpHandler httpHandler(ObjectProvider<WebFluxProperties> propsProvider) {
			HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(this.applicationContext).build();
			WebFluxProperties properties = propsProvider.getIfAvailable();
			if (properties != null && StringUtils.hasText(properties.getBasePath())) {
				Map<String, HttpHandler> handlersMap = Collections.singletonMap(properties.getBasePath(), httpHandler);
				return new ContextPathCompositeHandler(handlersMap);
			}
			return httpHandler;
		}
	}
}

可以看到這里注入了一個HttpHandler對象,難道就是HttpWebHandlerAdapter ,繼續(xù)往下看

首先調用了WebHttpHandlerBuilder.applicationContext(this.applicationContext)方法,點進去看

	public static WebHttpHandlerBuilder applicationContext(ApplicationContext context) {
		WebHttpHandlerBuilder builder = new WebHttpHandlerBuilder(
				context.getBean(WEB_HANDLER_BEAN_NAME, WebHandler.class), context);
	    ......
		return builder;		

可以看到通過context上下文對象通過beanName獲取bean來作為參數(shù)初始化WebHttpHandlerBuilder對象

/** Well-known name for the target WebHandler in the bean factory. */
public static final String WEB_HANDLER_BEAN_NAME = "webHandler";

而這個beanName正式前面說過的DispatcherHandler對象

	private WebHttpHandlerBuilder(WebHandler webHandler, @Nullable ApplicationContext applicationContext) {
		Assert.notNull(webHandler, "WebHandler must not be null");
		this.webHandler = webHandler;
		this.applicationContext = applicationContext;
	}

WebHttpHandlerBuilder中的webHandler屬性賦值為DispatcherHandler對象

接著進入build()方法,整體可以看到返回的HttpHandler對象就是HttpWebHandlerAdapter

	public HttpHandler build() {
		WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
		decorated = new ExceptionHandlingWebHandler(decorated,  this.exceptionHandlers);
		HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
		if (this.sessionManager != null) {
			adapted.setSessionManager(this.sessionManager);
		}
		if (this.codecConfigurer != null) {
			adapted.setCodecConfigurer(this.codecConfigurer);
		}
		if (this.localeContextResolver != null) {
			adapted.setLocaleContextResolver(this.localeContextResolver);
		}
		if (this.forwardedHeaderTransformer != null) {
			adapted.setForwardedHeaderTransformer(this.forwardedHeaderTransformer);
		}
		if (this.applicationContext != null) {
			adapted.setApplicationContext(this.applicationContext);
		}
		adapted.afterPropertiesSet();
		return (this.httpHandlerDecorator != null ? this.httpHandlerDecorator.apply(adapted) : adapted);
	}

首先看第一行

//這里的webHandler就是DispatcherHandler對象
WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
	public FilteringWebHandler(WebHandler handler, List<WebFilter> filters) {
		super(handler);
		this.chain = new DefaultWebFilterChain(handler, filters);
	}

調用父類的構造方法

private final WebHandler delegate;	
public WebHandlerDecorator(WebHandler delegate) {
		Assert.notNull(delegate, "'delegate' must not be null");
		this.delegate = delegate;
	}

此時將delegate賦值為DispatcherHandler對象

接著第二行

//此時入參中的decorated是FilteringWebHandler對象
decorated = new ExceptionHandlingWebHandler(decorated,  this.exceptionHandlers);
	public ExceptionHandlingWebHandler(WebHandler delegate, List<WebExceptionHandler> handlers) {
		super(delegate);
		List<WebExceptionHandler> handlersToUse = new ArrayList<>();
		handlersToUse.add(new CheckpointInsertingHandler());
		handlersToUse.addAll(handlers);
		this.exceptionHandlers = Collections.unmodifiableList(handlersToUse);
	}

再次調用父類的構造方法將此對象的父類中delegate屬性賦值為FilteringWebHandler對象

接著第三行

HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
	public HttpWebHandlerAdapter(WebHandler delegate) {
		super(delegate);
	}

一樣的道理將父類中delegate屬性賦值為ExceptionHandlingWebHandler對象

總結一下

HttpWebHandlerAdapter中delegate保存的是ExceptionHandlingWebHandler

ExceptionHandlingWebHandler中的delegate保存的是FilteringWebHandler

FilteringWebHandler中的delegate保存的是DispatcherHandler

到此這篇關于SpringCloud Gateway自動裝配實現(xiàn)流程詳解的文章就介紹到這了,更多相關SpringCloud Gateway內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java的文檔注釋之生成幫助文檔的實例

    Java的文檔注釋之生成幫助文檔的實例

    下面小編就為大家分享一篇Java的文檔注釋之生成幫助文檔的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • SpringBoot生成jar/war包的布局應用

    SpringBoot生成jar/war包的布局應用

    在 Spring Boot 中,"布局應用"(Application Layout)指的是打包生成的可執(zhí)行 jar 或 war 文件中的內容組織結構,本文給大家介紹了SpringBoot生成jar/war包的布局應用,需要的朋友可以參考下
    2024-02-02
  • java追加寫入txt文件的方法總結

    java追加寫入txt文件的方法總結

    在本篇文章里我們給大家整理了關于java如何追加寫入txt文件的方法和代碼,需要的朋友們可以參考下。
    2020-02-02
  • springboot中websocket簡單實現(xiàn)

    springboot中websocket簡單實現(xiàn)

    本文主要介紹了springboot中websocket簡單實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01
  • Maven之分析剔除無用的jar引用問題

    Maven之分析剔除無用的jar引用問題

    這篇文章主要介紹了Maven之分析剔除無用的jar引用問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 詳解Java實現(xiàn)LRU緩存

    詳解Java實現(xiàn)LRU緩存

    這篇文章主要介紹了詳解Java實現(xiàn)LRU緩存,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-08-08
  • OpenCV實現(xiàn)反閾值二值化

    OpenCV實現(xiàn)反閾值二值化

    這篇文章主要為大家詳細介紹了OpenCV實現(xiàn)反閾值二值化,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 一文解決pom.xml報錯Dependency "xxx" not found的問題

    一文解決pom.xml報錯Dependency "xxx" not f

    我們在使用maven進行jar包管理時有時會遇到pom.xml中報錯Dependency “XXX” not found,所以在本文中將給大家介紹一下pom.xml報錯Dependency "xxx" not found的解決方案,需要的朋友可以參考下
    2024-01-01
  • Eureka源碼閱讀解析Server服務端啟動流程實例

    Eureka源碼閱讀解析Server服務端啟動流程實例

    這篇文章主要為大家介紹了Eureka源碼閱讀解析Server服務端啟動流程實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-10-10
  • Java實現(xiàn)線程同步方法及原理詳解

    Java實現(xiàn)線程同步方法及原理詳解

    這篇文章主要介紹了Java實現(xiàn)線程同步方法及原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06

最新評論

孟连| 西宁市| 沾化县| 长治县| 富宁县| 龙泉市| 河池市| 沙田区| 全椒县| 崇州市| 巩留县| 长治市| 昌黎县| 奈曼旗| 衢州市| 蕲春县| 虞城县| 宁国市| 浏阳市| 肥西县| 太原市| 沿河| 那曲县| 康平县| 丹寨县| 益阳市| 正蓝旗| 云浮市| 象山县| 宁远县| 昌江| 南宁市| 黔东| 贵溪市| 永寿县| 威远县| 卓资县| 武平县| 陇西县| 岱山县| 临沂市|