Gateway网关(面试必问)

网关:

做转换任务的系统;本质是一个网络通向其它网络的IP地址,对收到的信息进行重新打包,以适应目的系统的需求。可用于不同通信协议,数据格式和语言,甚至不同体系结构的两种系统之间的互连

微服务网关:

给微服务中的所有服务提供同一的API访问入口,进行服务路由和相关处理;
 

Gateway网关:

官网:https://spring.io/projects/spring-cloud-gateway

概念:

官网概念解释:

This project provides a libraries for building an API Gateway on top of Spring WebFlux or Spring WebMVC. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.

译为:这个项目提供了一个库,用于在Spring WebFlux或Spring WebMVC之上构建API网关。 Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到api,并为它们提供横切关注点,例如:安全性、监控/指标和弹性。 

横切关注点:

我们直接可以想到spring中的AOP,即使用动态代理,不改变源码的基础上进行增强,这里的增强就是例如后面的功能;

我们可以简单的理解为:

在客户请求体和服务之间插入一道关卡,这个关卡类似为我们生活中的海关入口,要想将物品从海外进入到内地,必须进行海关检查等相关处理;

实际作用:

根据请求处理微服务中的服务调用;在单体架构中,服务调用很简单,不用过多处理,但是在微服务中,服务调用比较麻烦,因为有可能每个服务的语言和使用协议不同,所以得使用网关进行相关处理;

网关架构图:

Spring Cloud Gateway特点:

官网:

Spring Cloud Gateway features:

  • Built on Spring Framework and Spring Boot

  • Able to match routes on any request attribute.

  • Predicates and filters are specific to routes.

  • Circuit Breaker integration.

  • Spring Cloud DiscoveryClient integration

  • Easy to write Predicates and Filters

  • Request Rate Limiting

  • Path Rewriting

译:

基于spring框架的springboot;

能够匹配任何请求属性的路由;

谓词(断言)和过滤器可用于特定路由;

断路器集成;

Spring Cloud DiscoveryClient(服务发现)集成;

易于编写谓词和过滤器;

请求速率限制(限流);

路径重写;

在其基础上补充:

支持动态路由;

除了spring和springboot还基于Project Reactor(响应式编程)实现;

即Netty+Webflux实现;

Netty:一个基于NIO(同步非阻塞,I/O模型之一)的客户、服务器端的编程框架;

Webflux:响应式web框架,特点,完全非阻塞,底层基于NIO实现,可运行在Netty容器上(即容器不限制于servlet),也可于springMVC共存,但是mvc优先级高于Webflux;多用于高并发场景下。

注意事项:

Spring Cloud Gateway需要Spring Boot和Spring Webflux提供的Netty运行。 它不能在传统的Servlet容器中工作,也不能作为WAR构建。 

三大核心概念:

Route(路由):

网关的基本构建块。 它由一个ID、一个目标URI、一组谓词和一组过滤器定义。 如果聚合谓词为真,则匹配路由。 

即:Route=ID+URI+Predicates+Filters

URI:统一资源标识符;

URL:统一资源定位符;

这里使用URI是将资源网址暴露,资源具体位置在配置中指定,不然太乱;

Predicate(断言):

这是一个Java 8函数谓词。 输入类型为Spring Framework ServerWebExchange。 这可以匹配HTTP请求中的任何内容,例如标头或参数。 ServerWebExchange中包含了ServerHttpRequest。Predicate根据输入决定是否匹配路由。

Filters(过滤器):

这些是使用特定工厂构造的GatewayFilter实例。 在这里,可以在发送下游请求之前或之后修改请求和响应。 这里官网的解释用的“这些”这个词,因为它不是一个是一组,即过滤器链,这些过滤器主要用于过滤并处理请求,类似于springMVC的web过滤器。

支持重写数据,可以修改请求和返回的结果。

有两种类型:GlobalFilter,默认对所有路由生效;GatewayFilter,需要指定生效范围。

Spring Cloud Gateway 的工作原理:

Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a route, it is sent to the Gateway Web Handler. This handler runs the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line is that filters can run logic both before and after the proxy request is sent. All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.

释义:

客户端向Spring Cloud Gateway发出请求。如果网关处理程序映射确定请求与路由匹配,则将其发送到网关Web处理程序。此处理程序通过特定于请求的筛选器链运行请求。过滤器用虚线分隔的原因是过滤器可以在发送代理请求之前和之后运行逻辑。执行所有“预”过滤器逻辑。然后发出代理请求。发出代理请求后,将运行“post”过滤器逻辑。

详细执行流程:

1,客户端向网关微服务gateway发出请求;

2,进入Netty容器,DispatcherHandler(程序处理器)接受用户请求,开始处理程序;

3,路由映射器RoutePredicateHandlerMapping进行路由匹配,即程序中是否配置相关断言;

4,如果网关处理程序经过匹配发现与程序中设置的断言路由相匹配,则将请求发送给过滤器链处理程序处理FilteringWebHandler;如果不匹配,则发送会DispatcherHandler处理;

5,FilteringWebHandler通过特点过滤器发送请求,进入过滤器链,先执行“PRE”逻辑,然后进行代理请求,最后执行post逻辑;

6,FilteringWebHandler将请求发送到具体服务中;

7,FilteringWebHandler将服务处理结果返回给用户。

备注:

Spring Cloud Gateway中的Filter的生命周期为两种:PRE和POST

PRE:请求被路由之前执行(过滤器);可用来进行参数校验,权限校验,流量监控等相关功能;

POST:请求被路由之后(即路由到服务之后)执行(过滤器);可用于统计信息收集,响应头的修改,返回响应数据等;

DEMO01:配置文件配置断言

1,使用IDEA搭建maven环境(不带骨架):

2,导入Gateway依赖:


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

3,在resources文件中创建配置文件application.properties:


spring.application.name=Gateway Forward
server.port=8888
#日志配置:trace,配置debug和info都无法在控制台打印出路由信息
logging.level.root=trace
#id:配置路由自定义ID
spring.cloud.gateway.routes[0].id=hello
#uri:统一资源标识符(请求localhost:8888/hello时转发到此处)
spring.cloud.gateway.routes[0].uri=https://www.chinanews.com
#predicates:路由条件配置,即配置断言。Predicate会根据输入值返回一个布尔值
# 其包含多种默认方法将predicate组合成复杂的路由逻辑
spring.cloud.gateway.routes[0].predicates[0]=Path=/hello/**

这里注意:日志级别调整成trace,不然无法显示路由信息;

4,配置springboot启动类:


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

5,启动测试:

访问:http://localhost:8888/hello/zzn,页面能成功转发到指定页面即可;控制台打印部分如下:


Mapping [Exchange: GET http://localhost:8888/hello/zzn] to Route{id='hello', uri=https://www.chinanews.com:443, order=0, predicate=Paths: [/hello/**], match trailing slash: true, gatewayFilters=[], metadata={}}

DEMO02:JavaAPI配置路由

环境搭建和上面相同,唯一不同的是没有配置文件,而是在启动类中添加如下代码:@Bean


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

//    使用Java API的方式实现路由转发,即断言配置

    /**
     * .route("hello2",r->r.path("/hello2/**"))
     *                 .uri()
     *                 .build();
     */
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        return builder.routes()
                .route("hello2",r->r.path("/hello2/**")
                        .uri("https://www.chinanews.com"))
                .build();

    }
}

上面的就是路由方面配置,在spring cloud gateway中有专门的谓词工厂对路由规则进行了相关处理,共计11种,大家可以根据上述提供的官网地址进行查看,这里就不展开说明了。即通过RoutePredicateFactory 创建 Predicate。

路由规则匹配优先级:

根据权重匹配时,权重高的路由优先级高;

根据路由id匹配时,id值小的路由,优先级高;

当各种predicate同时存在同一个路由时,请求必须满足所有条件才会被此路由匹配。

DEMO03:网关注册到服务中心

微服务中,服务之间的相互调用非常频繁且繁琐,所以用服务中心组件进行统一管理,网关注册进服务中心后将代理转发服务,进行服务转发;

注册中心使用的是Consul:

官网下载地址:https://developer.hashicorp.com/consul/install?product_intent=consul#Windows

1,maven环境搭建;

2,引入依赖:


   <dependencies>
<!--        网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <version>3.1.4</version>
        </dependency>
<!--        服务中心:consul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <version>3.1.4</version>
        </dependency>
    </dependencies>

3,编写配置文件:application.properties


spring.application.name=Gateway-Consul
server.port=8889
#Consul的地址:默认localhost
spring.cloud.consul.host=localhost
#Consul的端口号:默认8500
spring.cloud.consul.port=8500
#网关是否与服务中心的发现组件结合
spring.cloud.gateway.discovery.locator.enabled=true
#日志配置
logging.level.org.springframework.cloud.gateway=debug

4,编写启动类:


@SpringBootApplication
@EnableDiscoveryClient//注册发现
public class GatewayConsulApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayConsulApplication.class,args);
    }
}

5,启动测试:

在consul.exe所在目录打开窗口使用指令consul agent -dev 打开consul,在consul界面发现名为Gateway-Consul服务通过检查即可;

上述只是网关基于路由的相关API展示,后续还有Filter过滤器相关,在官网也有过滤器工厂相关,大家可自行查看。

后续:

网关在实际应用中除了在注册中心中注册服务转发之外,还有路由容错熔断及限流,我会在后续中逐步更新,敬请期待。也可关注公众号“朱五斤”,微信公众号:CCSW19491001,二维码:

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值