SpringCloud-Gateway网关


前言

今天大致学了下SpringCloud中的getaway的内容


一、Gateway是什么

1、概述

Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能,例如:熔断、限流、重试等。
Spring Cloud Gateway的目标:提供统一的路由方式且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。
在这里插入图片描述

2、三大核心概念

  1. Route(路由):路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由
  2. Predicate(断言):参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
  3. Filter(过滤):指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改

3、工作原理

在这里插入图片描述
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 处理程序。此处理程序通过特定于请求的筛选器链运行请求。筛选器除以虚线的原因是筛选器可以在发送代理请求之前和之后运行逻辑。执行所有“pre”筛选器逻辑。然后发出代理请求。发出代理请求后,将运行“post”筛选器逻辑。

二、使用步骤

1、引入库

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

2、application.yml

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

        - id: payment_routh2 #payment_route    	#路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001          	#匹配后提供服务的路由地址,固定路由
          uri: lb://cloud-payment-service 		#匹配后提供服务的路由地址,动态路由:根据注册中心的服务名来动态访问
          predicates:
            - Path=/payment/lb/**         		#断言,路径相匹配的进行路由
            #- Header=X-Request-Id, \d+			#断言,要header,且为正数
            #- Cookie=username,sakanal			#断言,要包含cookie,且key=username,value=sakanal
            
        #如果路径为/api/C,则路由到B;如果路径为/api/A,则路由到A
        #但是如果AB的摆放顺序发生变动,则两个路径都只会路由到B,先匹配的先路由
        #在路由规则的顺序上,将精确的路由规则放置到模糊的路由规则的前面,
        #否则的话,精确的路由规则将不会被匹配到,类似于异常体系中try catch子句中异常的处理顺序。
        #可以使用order准确指定路由顺序
        - id: A
          uri: lb://A
          predicates:
            - Path=/api/A/**
        - id: B
          uri: lb://B
          predicates:
            - Path=/api/**
        
        #如果路径是/api/C,经过该路由会被过滤器改为/admin/C
        - id: C
          uri: lb://C
          predicates:  
            - Path=/api/** 
          filters:
            - RewritePath=/api/(?<segment>.*),/admin/$\{segment}


####################################################################
eureka:
  instance:
    instance-id: cloud-gateway-service
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      #单机模式(注册中心)
      defaultZone: http://eureka7001.com:7001/eureka/

3、主启动类

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

4、其他

编写配置类的方式来配置路由

@Configuration
public class GatewayConfig {
    /**
     * 配置了一个id为route-name的路由规则
     * 当访问地址为http://localhost:9527/guonei时会自动转发地址http://news.baidu.com/guonei
     * @param routeLocatorBuilder
     * @return
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        routes.route("path_route_atguigu",
                r -> r.path("/guonei")//===>predicates:  - Path=/guonei
                      .uri("http://news.baidu.com/guonei"))//===>uri: http://news.baidu.com/guonei
                      .build();
        return routes.build();
    }
}

5、总结

在使用gateway后,可以通过网关来决定(是否/如何/…)调用服务
不必暴露实际服务的接口或地址,而是暴露网关的接口。就像将所有服务套一层壳,可以一定程度上的保护服务

三、Gateway的Predicate

官方文档

Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure.
Spring Cloud Gateway includes many built-in route predicate factories. All of these predicates match on different attributes of the HTTP request.
You can combine multiple route predicate factories with logical and statements.

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

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

Spring Cloud Gateway创建Route 对象时,使用RoutePredicateFactory 创建 Predicate对象,Predicate 对象可以赋值给Route。Spring Cloud Gateway包含许多内置的Route Predicate Factories。
所有这些谓词都匹配HTTP请求的不同属性。多种谓词工厂可以组合,并通过逻辑and拼接。

常用的Route Predicate Factory

  1. The After Route Predicate Factory
    – After=2017-01-20T17:42:47.789-07:00[America/Denver]
    – 采用一个参数,即日期时间。此route predicate匹配在指定日期时间之后发生的请求。

  2. The Before Route Predicate Factory
    – Before=2017-01-20T17:42:47.789-07:00[America/Denver]
    – 采用一个参数,即日期时间。此route predicate匹配在指定日期时间之前发生的请求。

  3. The Between Route Predicate Factory
    – Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
    – 采用一个参数,即日期时间。此route predicate匹配在指定日期时间之间发生的请求。

  4. The Cookie Route Predicate Factory
    – Cookie=chocolate, ch.p
    – 采用两个参数,即 cookie 名称和正则表达式。此route predicate匹配具有给定名称且其值与正则表达式匹配的 Cookie

  5. The Header Route Predicate Factory
    – Header=X-Request-Id, \d+
    – 采用两个参数:标头名称和正则表达式。此route predicate与具有给定名称的标头匹配,其值与正则表达式匹配

  6. The Host Route Predicate Factory
    – Host=**.somehost.org,**.anotherhost.org
    – 采用一个参数:主机名模式列表。该模式是作为分隔符的 Ant 样式模式。此route predicate与与模式匹配的标头匹配。

  7. The Method Route Predicate Factory
    – Method=GET,POST
    – 采用一个或多个参数:要匹配的 HTTP 方法。

  8. The Path Route Predicate Factory
    – Path=/red/{segment},/blue/{segment}
    – 采用两个参数:Spring 模式列表和名为 的可选标志。

  9. The Query Route Predicate Factory
    – Query=green
    – 采用两个参数:必需参数和可选参数。

  10. The RemoteAddr Route Predicate Factory
    – RemoteAddr=192.168.1.1/24
    – 采用 CIDR 表示法(IPv4 或 IPv6)字符串的列表(最小大小 1),例如(其中是 IP 地址,是子网掩码)

  11. The weight Route Predicate Factory
    – Weight=group1, 2
    – 采用两个参数:组和权重。权重是按组计算的

四、Gateway的Filter

官方文档

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

1、概览

路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。Spring Cloud Gateway内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生。

  • 生命周期
    • pre
    • post
  • 种类
    • GatewayFilter - 有31种
    • GlobalFilter - 有10种

常用的GatewayFilter:AddRequestParameter GatewayFilter

2、自定义全局GlobalFilter

两个主要接口介绍:

  • GlobalFilter
  • Ordered

能干什么:

  • 全局日志记录
  • 统一网关鉴权

3、自定义全局Filter案例

@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 uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if(uname == null){
            log.info("*******用户名为null,非法用户,o(╥﹏╥)o");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder(){
        return 0;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值