zoukankan      html  css  js  c++  java
  • spring Cloud-gateWay 进行API网关转发

    1 SpringCloud Gateway 简介

    SpringCloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。

    SpringCloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Zuul,在Spring Cloud 2.0以上版本中,没有对新版本的Zuul 2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 2.0之前的非Reactor模式的老版本。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。

    Spring Cloud Gateway 的目标,不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。

    提前声明:Spring Cloud Gateway 底层使用了高性能的通信框架Netty

    引入依赖:

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- 需要注册到eureka -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    2 Spring Cloud Gateway路由配置方式

    yaml文件配置

    server:
      port: 8080
    spring:
      application:
        name: api-gateway
      cloud:
        gateway:
          routes:
            -id: url-proxy-1
              uri: https://blog.csdn.net
              predicates:
                -Path=/csdn

    各字段含义如下:

    id:我们自定义的路由 ID,保持唯一

    uri:目标服务地址

    predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。

    上面这段配置的意思是,配置了一个 id 为 url-proxy-1的URI代理规则,

    路由的规则为:

    当访问地址http://localhost:8080/csdn/1.jsp时,会路由到上游地址https://blog.csdn.net/1.jsp。

    基于代码的路由配置方式

    转发功能同样可以通过代码来实现,我们可以在启动类 GateWayApplication 中添加方法 customRouteLocator() 来定制转发规则。

    package com.springcloud.gateway;
     
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.gateway.route.RouteLocator;
    import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
    import org.springframework.context.annotation.Bean;
     
    @SpringBootApplication
    public class GatewayApplication {
     
        public static void main(String[] args) {
            SpringApplication.run(GatewayApplication.class, args);
        }
     
        @Bean
        public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
            return builder.routes()
                    .route("path_route", r -> r.path("/csdn")
                            .uri("https://blog.csdn.net"))
                    .build();
        }
     
    }

    3.Predicate的配置使用

    Predicate 就是为了实现一组匹配规则,方便让请求过来找到对应的 Route 进行处理

    1.通过请求参数匹配

    Query Route Predicate 支持传入两个参数,一个是属性名一个为属性值,属性值可以是正则表达式。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            -Query=smile

    这样配置,只要请求中包含 smile 属性的参数即可匹配路由。

    使用 curl 测试,命令行输入:

    curl localhost:8080?smile=x&id=2

    经过测试发现只要请求汇总带有 smile 参数即会匹配路由,不带 smile 参数则不会匹配。

    还可以将 Query 的值以键值对的方式进行配置,这样在请求过来时会对属性值和正则进行匹配,匹配上才会走路由

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            -Query=keep, pu.

    这样只要当请求中包含 keep 属性并且参数值是以 pu 开头的长度为三位的字符串才会进行匹配和路由。

    使用 curl 测试,命令行输入:

    curl localhost:8080?keep=pub

    测试可以返回页面代码,将 keep 的属性值改为 pubx 再次访问就会报 404,证明路由需要匹配正则表达式才会进行路由。

    2.通过 Header 属性匹配

    Header Route Predicate 和 Cookie Route Predicate 一样,也是接收 2 个参数,一个 header 中属性名称和一个正则表达式,这个属性值和正则表达式匹配则执行。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            - Header=X-Request-Id, d+

    使用 curl 测试,命令行输入:

    curl http://localhost:8080 -H "X-Request-Id:88"

    则返回页面代码证明匹配成功。将参数-H "X-Request-Id:88"改为-H "X-Request-Id:spring"再次执行时返回404证明没有匹配。

    3.通过 Cookie 匹配

    Cookie Route Predicate 可以接收两个参数,一个是 Cookie name ,一个是正则表达式,路由规则会通过获取对应的 Cookie name 值和正则表达式去匹配,如果匹配上就会执行路由,如果没有匹配上则不执行。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            - Cookie=sessionId, test

    使用 curl 测试,命令行输入:

    curl http://localhost:8080 --cookie "sessionId=test"

    则会返回页面代码,如果去掉--cookie "sessionId=test",后台汇报 404 错误。

    4.通过 Host 匹配

    Host Route Predicate 接收一组参数,一组匹配的域名列表,这个模板是一个 ant 分隔的模板,用.号作为分隔符。它通过参数中的主机地址作为匹配规则。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            - Host=**.baidu.com

    使用 curl 测试,命令行输入:

    curl http://localhost:8080 -H "Host: www.baidu.com"

    curl http://localhost:8080 -H "Host: md.baidu.com"

    经测试以上两种 host 均可匹配到 host_route 路由,去掉 host 参数则会报 404 错误。

    6 通过请求方式匹配

    可以通过是 POST、GET、PUT、DELETE 等不同的请求方式来进行路由。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            - Method=GET

    使用 curl 测试,命令行输入:

    # curl 默认是以 GET 的方式去请求

    curl http://localhost:8080

    测试返回页面代码,证明匹配到路由,我们再以 POST 的方式请求测试。

    # curl 默认是以 GET 的方式去请求

    curl -X POST http://localhost:8080

    返回 404 没有找到,证明没有匹配上路由

    7 通过请求路径匹配

    Path Route Predicate 接收一个匹配路径的参数来判断是否走路由。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        -id: gateway-service
    ​          uri: http://ityouknow.com
    ​          order: 0
    ​          predicates:
    ​            -Path=/foo/{segment}

    如果请求路径符合要求,则此路由将匹配,例如:/foo/1 或者 /foo/bar。

    使用 curl 测试,命令行输入:

    curl http://localhost:8080/foo/1

    curl http://localhost:8080/foo/xx

    curl http://localhost:8080/boo/xx

    经过测试第一和第二条命令可以正常获取到页面返回值,最后一个命令报404,证明路由是通过指定路由来匹配。

    8 通过请求 ip 地址进行匹配

    Predicate 也支持通过设置某个 ip 区间号段的请求才会路由,RemoteAddr Route Predicate 接受 cidr 符号(IPv4 或 IPv6 )字符串的列表(最小大小为1),例如 192.168.0.1/16 (其中 192.168.0.1 是 IP 地址,16 是子网掩码)。

    server:
      port: 8080
    spring:
      application:
    ​    name: api-gateway
      cloud:
    ​    gateway:
    ​      routes:
    ​        - id: gateway-service
    ​          uri: https://www.baidu.com
    ​          order: 0
    ​          predicates:
    ​            - RemoteAddr=192.168.1.1/24

    可以将此地址设置为本机的 ip 地址进行测试。

    curl localhost:8080

    如果请求的远程地址是 192.168.1.10,则此路由将匹配。

    组合使用的例子:

    server:
      port: 8080
    spring:
      application:
        name: api-gateway
      cloud:
        gateway:
          routes:
            - id: gateway-service
              uri: https://www.baidu.com
              order: 0
              predicates:
                - Host=**.foo.org
                - Path=/headers
                - Method=GET
                - Header=X-Request-Id, d+
                - Query=foo, ba.
                - Query=baz
                - Cookie=chocolate, ch.p

    predicates的官方参考:
            # 匹配在什么时间之后的
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]
            # 匹配在什么时间之前的
            - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
            # 匹配在某段时间的
            - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
            # 匹配cookie名称为`chocolate`的值要符合`ch.p`正则.
            - Cookie=chocolate, ch.p
            # 匹配header为`X-Request-Id`的值要符合`d+`正则.
            - Header=X-Request-Id, d+
            # 匹配任意符合`**.somehost.org`与`**.anotherhost.org`正则的网址
            - Host=**.somehost.org,**.anotherhost.org
            # Host还支持模版变量,会保存在`ServerWebExchange.getAttributes()`的 ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE中,以Map形式存储
            - Host={sub}.myhost.org
            # 匹配GET方法
            - Method=GET
            # 路径匹配,与Host一样支持模版变量,存在URI_TEMPLATE_VARIABLES_ATTRIBUTE中。
            - Path=/foo/{segment},/bar/{segment}
            # 匹配存在baz查询参数
            - Query=baz
            # 匹配存在foo且符合`ba.`正则
            - Query=foo, ba.
            # 匹配远程地址
            - RemoteAddr=192.168.1.1/24
    
    
    

    4.和注册中心相结合的路由配置方式

    在uri的schema协议部分为自定义的lb:类型,表示从微服务注册中心(如Eureka)订阅服务,并且进行服务的路由。

    一个典型的示例如下:

    server:
      port: 8084
    spring:
      cloud:
        gateway:
          routes:
          -id: seckill-provider-route
            uri: lb://seckill-provider
            predicates:
            - Path=/seckill-provider/**
    
          -id: message-provider-route
            uri: lb://message-provider
            predicates:
            -Path=/message-provider/**
    
    application:
      name: cloud-gateway
    
    eureka:
      instance:
        prefer-ip-address: true
      client:
        service-url:
          defaultZone: http://localhost:8888/eureka/

    注册中心相结合的路由配置方式,与单个URI的路由配置,区别其实很小,仅仅在于URI的schema协议不同。单个URI的地址的schema协议,一般为http或者https协议。

    5.高级功能-实现熔断降级

    为什么要实现熔断降级?

    在分布式系统中,网关作为流量的入口,因此会有大量的请求进入网关,向其他服务发起调用,其他服务不可避免的会出现调用失败(超时、异常),失败时不能让请求堆积在网关上,需要快速失败并返回给客户端,想要实现这个要求,就必须在网关上做熔断、降级操作。

    server.port: 8082
    
    spring:
      application:
        name: gateway
      redis:
          host: localhost
          port: 6379
          password: 123456
      cloud:
        gateway:
          routes:
            - id: rateLimit_route
              uri: http://localhost:8000
              order: 0
              predicates:
                - Path=/test/**
              filters:
                - StripPrefix=1
                - name: Hystrix
                  args:
                    name: fallbackCmdA
                    fallbackUri: forward:/fallbackA
    
    hystrix.command.fallbackCmdA.execution.isolation.thread.timeoutInMilliseconds: 5000

    这里的配置,使用了两个过滤器:

    (1)过滤器StripPrefix,作用是去掉请求路径的最前面n个部分截取掉。

    StripPrefix=1就代表截取路径的个数为1,比如前端过来请求/test/good/1/view,匹配成功后,路由到后端的请求路径就会变成http://localhost:8888/good/1/view。

    (2)过滤器Hystrix,作用是通过Hystrix进行熔断降级

    当上游的请求,进入了Hystrix熔断降级机制时,就会调用fallbackUri配置的降级地址。需要注意的是,还需要单独设置Hystrix的commandKey的超时时间

    fallbackUri配置的降级地址的代码如下:

    package org.gateway.controller;
    
    import org.gateway.response.Response;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class FallbackController {
    
        @GetMapping("/fallbackA")
        public Response fallbackA() {
            Response response = new Response();
            response.setCode("100");
            response.setMessage("服务暂时不可用");
            return response;
        }
    }
    View Code

    6.高级功能-分布式限流

    这边就不拓展了

    转载自:https://www.cnblogs.com/crazymakercircle/p/11704077.html

  • 相关阅读:
    Windows环境下使用cygwin ndk_r9c编译FFmpeg
    android 开发环境搭建
    POJ 2559 单调栈入门,三种代码实现
    poj 2100 尺取法(尺度法)
    尺取算法 入门+模板+例题
    POJ 3579 Median 二分+思维
    POJ 3685 Matrix 二分套二分
    CodeForces 371C Hamburgers 二分
    HDU 4355 Party All the Time 三分算法
    HDU 3613 Best Reward Manacher算法
  • 原文地址:https://www.cnblogs.com/linhongwenBlog/p/12549596.html
Copyright © 2011-2022 走看看