SpringCloud课程:18.Gateway 网关服务

原创
2020/12/04 22:58
阅读数 1.5W

Gateway 网关服务

一、概述

Gateway是在Spring生态系统之上构建的API网关系统,基于Spring5 Springboot2 和Project Reactor等技术
Gateway旨在提供一种简单而有效的方式来对API进行路由 ,以及提供一些强大的过滤器功能,例如熔断、限流、重试等。

 

二、作用

作用
    反向代理
    鉴权
    流量控制
    熔断
    日志监控

三、三大核心概念

  • Route(路由)

    路由是构建网关的基本模块,由ID,URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由

  • Predicate 断言

    参考java8的java.util.function.Predicate
开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由

  • Filter 过滤

    指Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或之后对请求进行修改

总结:

web请求通过一些匹配条件,定位到真正的服务节点。并在这个转发过程的前后,进行一些精细化控制
predicate就是我们的匹配条件,
而Filter可以理解为一个无所不能的过滤器,有了这两个元素再加上目标Uri 就可以实现一个具体的路由。

四、Gateway工作流

客户端向SpringCloudGateway发出请求。然后在GatewayHandlerMapping中找到与请求相匹配的路由,将其发送到GatewayWebHandler.

Handle再通过指定的过滤链来将请求发送到我们实际的服务执行业务逻辑 ,然后返回。
过滤器可能会在发送代理请求之前"pre" 或之后 “post”执行业务逻辑

Filter在“pre”类型的过滤器可以做参数校验、权限校验、流量控制、日志输出、协议转换等,在“post”类型的过滤器可以做响应内容、响应头的修改,日志的输出,流量监控等有非常重要的作用

五、入门配置

1.新建module cloud-gateway-gateway9527

2.pom

需要移除spring-boot-starter-web 否则报错
    Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

 <dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.yml

server:
  port: 9527
spring:
  application:
    name: cloud-gateway

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

4.main

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

5.通过网关访问8001的接口

映射两个接口

/payment/lb

/payment/get/{id}

YML新增网关配置:

    新增spring.cloud.gateway.routes部分

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001          #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**         # 断言,路径相匹配的进行路由
        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001          #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

 

启动7001、cloud-provider-payment8001、9527

访问
    http://localhost:9527/payment/get/1

6.YML配置说明

Gateway网关路由有两种配置方式

6.1 在YML中配置

6.2 代码中注入RouteLocator的Bean

参考:https://spring.io/projects/spring-cloud-gateway

com.zhl.springcloud.config.GateWayConfig

@Configuration
public class GateWayConfig {
    @Bean
    public RouteLocator customeRouteLocator(RouteLocatorBuilder builder){
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route_atguigu1",
                r->r.path("/guonei")
                        .uri("http://news.baidu.com/guonei")).build();
        return  routes.build();
    }
}

6.3 测试访问

    http://localhost:9527/guonei 跳转 http://news.baidu.com/guonei

六、通过微服务名实现动态路由

默认情况下GateWay会根据注册中心注册的服务列表
以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能。

1.启动Eureka和服务提供者 8001 8002

2.YML

    1.spring.cloud.gateway.discovery.locator.enabled:true

    2.spring.cloud.gateway.routes[0].uri:lb://cloud-payment-service #匹配后提供服务的路由地址

        spring.cloud.gateway.routes[1].uri:lb://cloud-payment-service

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**         # 断言,路径相匹配的进行路由

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**         # 断言,路径相匹配的进行路由

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

3.测试

访问:http://localhost:9527/payment/lb   

8001/8002

七、Predicate的使用

1.Predicate是什么

 

2.RoutePredicateFactories 是什么

查看启动的后台信息:

Spring Cloud Gateway将路由匹配作为SpringWebFlux HandlerMapping基础架构的一部分

Spring Cloud Gateway 包括许多内置的Route Predicate工厂。所有这些Predicate都与HTTP请求的不同属性匹配。多个RoutePredicate工厂可以进行组合

Spring Cloud Gateway创建Route对象时,使用RoutePredicateFactory创建Predicate对象,Predicate对象可以赋值给Route。SpringCloudGateway包含许多内置的RoutePredicateFatories

3. 常用的Route Predicate

参考官网:

https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/#gateway-request-predicates-factories

 

1.After Route Predicate
    在时间之后  使用 ZonedDateTime.now() 获取时间

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001          #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
            - After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]

2.Before Route Predicate
    在时间之前
3.Between Route Predicate
    时间之间
4.Cookie Route Predicate

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001          #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
            #- After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]
            - Cookie=username,zzyy

  不带cookie访问 

C:\Users\Administrator>curl http://localhost:9527/payment/lb
{"timestamp":"2020-12-04T14:16:14.906+00:00","path":"/payment/lb","status":404,"error":"Not Found",......

   带上cookie访问 

C:\Users\Administrator>curl http://localhost:9527/payment/lb  --cookie "username=zzyy"
8002

5.Header

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
            - Header=X-Request-Id, \d+  # 请求头要有X-Request-Id属性并且值为整数的正则表达式
C:\Users\Administrator>curl http://localhost:9527/payment/lb  -H "X-Request-Id:1234"
8002
C:\Users\Administrator>curl http://localhost:9527/payment/lb  -H "X-Request-Id:aaaa"
{"timestamp":"2020-12-04T14:22:01.354+00:00","path":"/payment/lb","status":404,"error":"Not Found",

 

6.Host

Host Route Predicate接收一组参数,一组匹配的域名列表,这个模板时一个ant分割的模板,用.号作为分隔符它通过参数中的主机地址作为匹配规则。
7.Method
8.Path
9.Query
10.小结

八、Filter的使用

指的是Spring框架中GatewayFilter的实例,使用过滤器,可以再请求被路由前或之后对请求进行修改。

路由过滤器允许以某种方式修改传入的HTTP请求或传出的HTTP响应。路由过滤器适用于特定路由。Spring Cloud Gateway包括许多内置的GatewayFilter工厂

1.声明周期

    Pre  Post

2.种类

GatewayFilter:     单一的
GlobalFilter:        全局的

3.常用的GatewayFilter

    AddRequestParameter

4.自定义过滤器

A. 两个主要接口

B.作用

    全局日志记录

    统一网关鉴权...

C.案例代码

新增 组件 :com.zhl.springcloud.filter.MyLogGateWayFilter

@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("*****come in MyLogGateWayFilter: "+new Date());
        String name =exchange.getRequest().getQueryParams().getFirst("uname");
        if (name==null){
            log.info("***用户名为null ,非法用户***");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        /*加载过滤器的顺序,顺序越小优先级越高*/
        return 0;
    }
}

D.测试

C:\Users\Administrator>curl http://localhost:9527/payment/lb?uname=z3
8002

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
10 收藏
3
分享
返回顶部
顶部