欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Cloud 新一代网关:Spring Cloud GateWay

程序员文章站 2022-07-14 23:18:23
...

简介

为什么用网关?

Spring Cloud GateWay的核心执行逻辑

示例编写

父pom

依赖项目gateway的pom

application.yml

启动项

启动日志


简介

简单点说:Spring Cloud GateWay就像医院里分诊台,将你引导到各个科室

Spring Cloud GateWay提供了一套简单有效的API路由管理方式,是基于Filter(过滤器)的方式提供网关的基本功能

作用:

  • 安全验证
  • 监控
  • 限流
  • 熔断
  • 重试等

Netflix Zuul 由于Netflix公司迟迟不更新2.0,开发者已经对它失去信心了,反正我是失去了,Spring Cloud GateWay会一步一步的取代Zuul

为什么用网关?

服务网关 = 路由转发 + 过滤器

1、路由转发:接收一切外界请求,转发到后端的微服务上去;

2、过滤器:在服务网关中可以完成一系列的横切功能,例如权限校验、限流以及监控等,这些都可以通过过滤器完成(其实路由转发也是通过过滤器实现的);

假设你开发一个电商服务,有会员,支付,商品等等服务

  • 你会对每个服务都进行鉴权、限流、权限校验等逻辑?
  • 每次上线一个服务都要申请域名,配置Nginx等等?
  • 每个服务可能用不同的开发语言编写,那么可能会采用不同的协议,例如Dubbo,HTTP等,你也要适配这些协议?
  • 商品服务业务量越来越大,需要拆分,那么需要客户端配合改造,这也是非常蛋疼的事情

这个时候网管服务就起作用了,类似Nginx的作用,将所有用户的请求转发给后端的服务器,但网关做的不仅仅只是简单的转发,也会针对流量做一些扩展,比如鉴权、限流、权限、熔断、协议转换、错误码统一、缓存、日志、监控、告警等,这样将通用的逻辑抽出来,由网关统一去做,业务方也能够更专注于业务逻辑,提升迭代的效率。

Spring Cloud 新一代网关:Spring Cloud GateWay

Spring Cloud GateWay的核心执行逻辑

核心逻辑 = 断言(Predicate:断言是否为true才允许转发) + 路由转发(Route) + 执行过滤链(Filter )

Spring Cloud 新一代网关:Spring Cloud GateWay

官网提供执行图:

Spring Cloud 新一代网关:Spring Cloud GateWay

Spring Cloud 新一代网关:Spring Cloud GateWay

执行流程:

  • ① Gateway 接收客户端请求。

  • ② 请求与 Predicate 进行匹配,获得到对应的 Route。匹配成功后,才能继续往下执行。

  • ③ 请求经过 Filter 过滤器链,执行前置(prev)处理逻辑。

    例如说,修改请求头信息等。

  • ④ 请求被 Proxy Filter 转发至目标 URI,并最终获得响应。

    一般来说,目标 URI 是被代理的微服务,如果是在 Spring Cloud 架构中。

  • ⑤ 响应经过 Filter 过滤器链,执行后置(post)处理逻辑。

  • ⑥ Gateway 返回响应给客户端。

其实,就类似就像SpringMVC 的 DispatcherServlet差不多,只是说 SpringMVC 最终转发到 JVM 进程内的指定方法,而 Gateway 最终转发到远程的目标 URI 

下面是一张更清楚的流程图:

Spring Cloud 新一代网关:Spring Cloud GateWay

示例编写

父pom

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.cloud.work</groupId>
	<artifactId>work-cloud</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>pom</packaging>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<java.version>1.8</java.version>
		<spring-cloud-alibaba.version>2.2.0.RELEASE</spring-cloud-alibaba.version>
		<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
		<spring-boot.version>2.3.0.RELEASE</spring-boot.version>
	</properties>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>com.alibaba.cloud</groupId>
				<artifactId>spring-cloud-alibaba-dependencies</artifactId>
				<version>${spring-cloud-alibaba.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>${spring-boot.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
		</repository>
	</repositories>

	<modules>
		<module>cloud-gateway</module>
	</modules>
</project>

依赖项目gateway的pom

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.cloud.work</groupId>
		<artifactId>work-cloud</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>
	<artifactId>cloud-gateway</artifactId>
	
	<dependencies>
        <!-- 引入 Spring Cloud Gateway 相关依赖,使用它作为网关,并实现对其的自动配置 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>
</project>

application.yml

server:
  port: 8081

spring:
  cloud:
    # Spring Cloud Gateway 配置项,对应 GatewayProperties 类
    gateway:
      # 路由配置项,对应 RouteDefinition 数组
      routes:
        - id: yudaoyuanma # 路由的编号
          uri: https://www.baidu.com # 路由到的目标地址
          predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
            - Path=/blog
          filters:
            - StripPrefix=1
        - id: oschina # 路由的编号
          uri: https://www.oschina.net # 路由的目标地址
          predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
            - Path=/oschina
          filters: # 过滤器,对请求进行拦截,实现自定义的功能,对应 FilterDefinition 数组
            - StripPrefix=1

启动项

package com.cloud.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

启动日志


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.0.RELEASE)

2020-11-29 13:12:34.666  INFO 19664 --- [           main] com.cloud.gateway.GatewayApplication     : No active profile set, falling back to default profiles: default
2020-11-29 13:12:35.535  INFO 19664 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=83925bed-0b21-326e-a5b0-784d1d4030ed
2020-11-29 13:12:35.639  INFO 19664 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-11-29 13:12:35.640  INFO 19664 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactiveLoadBalancerConfig' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactiveLoadBalancerConfig] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-11-29 13:12:35.644  INFO 19664 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'deferringLoadBalancerExchangeFilterFunction' of type [org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-11-29 13:12:35.851  WARN 19664 --- [           main] o.s.c.n.a.ArchaiusAutoConfiguration      : No spring.application.name found, defaulting to 'application'
2020-11-29 13:12:35.857  WARN 19664 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2020-11-29 13:12:35.857  INFO 19664 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2020-11-29 13:12:35.863  WARN 19664 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2020-11-29 13:12:35.863  INFO 19664 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2020-11-29 13:12:43.204  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [After]
2020-11-29 13:12:43.204  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Before]
2020-11-29 13:12:43.204  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Between]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Cookie]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Header]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Host]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Method]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Path]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Query]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [ReadBodyPredicateFactory]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [RemoteAddr]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [Weight]
2020-11-29 13:12:43.205  INFO 19664 --- [           main] o.s.c.g.r.RouteDefinitionRouteLocator    : Loaded RoutePredicateFactory [CloudFoundryRouteService]
2020-11-29 13:12:43.562  INFO 19664 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'Nacso-Watch-Task-Scheduler'
2020-11-29 13:12:48.231  INFO 19664 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8888
2020-11-29 13:12:51.969  WARN 19664 --- [           main] c.a.c.n.registry.NacosServiceRegistry    : No service to register for nacos client...
2020-11-29 13:12:52.005  INFO 19664 --- [           main] com.cloud.gateway.GatewayApplication     : Started GatewayApplication in 21.601 seconds (JVM running for 22.549)

使用浏览器,访问 http://127.0.0.1:8888/blog,成功转发到目标 URI https://www.baidu.com,如下图所示:

 

Spring Cloud 新一代网关:Spring Cloud GateWay