GateWay网关应用案例(跨域、限流、黑白名单)

Spring Cloud Gateway是基于Spring Boot 2.xSpring WebFluxProject Reactor 构建的。属于异步非阻塞架构

Spring Cloud Gateway与Spring Data 和Spring Securit 技术不能同时使用

Spring Cloud Gateway基于Spring Boot和Spring Webflux提供的Netty运行。它在传统的Servlet容器中或用WAR的方式构建时不起作用

网关基本的功能 :鉴权、流量控制、熔断、路径重写、⽇志监控等

GateWay核心概念

  • 路由(route): 网关最基础的部分,也是网关比较基础的工作单元。
    路由由一个ID、一个目标 URL(最终路由到的地址)、一系列的断言(匹配条件判断)和Filter过滤器(精细化控制)组成。
    如果断言为true,则匹配该路由。

  • 断言(predicates):参考了Java8中的断言java.util.function.Predicate
    开发人员可以匹配Http 请求中的所有内容(包括请求头、请求参数等)(类似于Nginx中的location匹配一样)
    如果断言与请求相匹配则路由。

  • 过滤器(filter):⼀个标准的Spring webFilter,使用过滤器,可以在请求之前或者之后执行业务逻辑。

GateWay工作过程

在这里插入图片描述

解释

客户端向Spring Cloud GateWay发出请求,然后在GateWay Handler Mapping中找到与请求相匹配的路由,将其发送到GateWay Web Handler;
Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。

过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(pre)或者之后(post)执行业务逻辑。

Filter在“pre”类型过滤器中可以做参数校验、权限校验、流量监控、日志输出、协议转换等;
在“post”类型的过滤器中可以做响应内容、响应头的修改、日志的输出、流量监控等。

GateWay应用

GateWay不需要使用web模块,它引入的是WebFlux(类似于SpringMVC)

 <!--GateWay ⽹关-->
 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
 </dependency>
<!--引⼊webflux-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

application.yml

server:
  port: 88

spring:
  application:
    name: payment-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes: # 路由可以有多个
        ##产品服务路由器,拦截/api/product请求,并重写url地址
        - id: product_route             # ⾃定义的路由 ID,保持唯⼀
          uri: lb://payment-product    # ⽬标服务地址  lb表是负载均衡,payment-product 服务名
          predicates:                   # 断言
            - Path=/api/product/**
          filters:                      # 过滤器
            - RewritePath=/api/(?<segment>/?.*), /$\{
   
   segment}

GateWay断言详解

Spring Cloud GateWay 帮我们内置了很多 Predicates功能,实现了各种路由匹配规则

在这里插入图片描述

时间点后匹配 :

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]

时间点前匹配 :

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

时间区间匹配 :

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: http
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值