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

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

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

啟動依賴

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

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

點(diǎn)進(jìn)去之后找到它的依賴

  <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的核心依賴,找到依賴包,看到如下結(jié)構(gòu)

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,負(fù)責(zé)很多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 導(dǎo)入了 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();
}

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

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

可以看到DispatcherHandler實(shí)現(xiàn)了WebHandler接口并實(shí)現(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應(yīng)該就是核心的處理方法,此時(shí)又有疑問,該方法什么時(shí)候被調(diào)用,被誰調(diào)用的

官方文檔上提到WebHandler 上面還有一個關(guān)鍵的 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 來調(diào)用 WebHandler (請求由下往上),那DispatcherHandler作為 WebHandler 的一個實(shí)現(xiàn),也很有可能會被HttpHandler的具體實(shí)現(xiàn)所持有。

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

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

總之,我們找到了調(diào)用 DispatcherHandher 的地方了,那下一步我們要找 HttpWebHandlerAdapter 是在哪里被裝配的,并且webHandler 是是什么時(shí)候被注入的,注入的 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ù)往下看

首先調(diào)用了WebHttpHandlerBuilder.applicationContext(this.applicationContext)方法,點(diǎn)進(jìn)去看

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

接著進(jìn)入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);
	}

調(diào)用父類的構(gòu)造方法

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

此時(shí)將delegate賦值為DispatcherHandler對象

接著第二行

//此時(shí)入?yún)⒅械膁ecorated是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);
	}

再次調(diào)用父類的構(gòu)造方法將此對象的父類中delegate屬性賦值為FilteringWebHandler對象

接著第三行

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

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

總結(jié)一下

HttpWebHandlerAdapter中delegate保存的是ExceptionHandlingWebHandler

ExceptionHandlingWebHandler中的delegate保存的是FilteringWebHandler

FilteringWebHandler中的delegate保存的是DispatcherHandler

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

相關(guān)文章

  • Java的文檔注釋之生成幫助文檔的實(shí)例

    Java的文檔注釋之生成幫助文檔的實(shí)例

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

    SpringBoot生成jar/war包的布局應(yīng)用

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

    java追加寫入txt文件的方法總結(jié)

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

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

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

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

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

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

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

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

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

    一文解決pom.xml報(bào)錯Dependency "xxx" not f

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

    Eureka源碼閱讀解析Server服務(wù)端啟動流程實(shí)例

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

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

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

最新評論

壤塘县| 嘉黎县| 灵丘县| 宣恩县| 怀集县| 墨玉县| 崇信县| 富源县| 巴中市| 常宁市| 玉门市| 阳春市| 于都县| 睢宁县| 时尚| 通辽市| 南和县| 旬阳县| 铜梁县| 芜湖市| 新宾| 大竹县| 伊春市| 鄂温| 合山市| 天等县| 彰武县| 广南县| 双城市| 宾阳县| 台湾省| 万年县| 普定县| 灵石县| 当阳市| 安国市| 资源县| 涞源县| 湖口县| 六盘水市| 北流市|