Spring Cloud Gateway:
一、基本概念:
Route
  •  id:路由标识、区别于其他route
  • uri:路由指向的目的地uri,即客户端请求最终被转发到的微服务
  • order:用于多个route之间的排序,数值越小排序越靠前,匹配优先级越高
  • predicate:断言的作用是进行条件判断,只有断言都返回真,才会真正的执行路由 
  • filter:过滤器用于修改请求和响应信息
二、执行流程
  1. Gateway Client向Gateway Server发送请求
  2. 请求首先会被HttpWebHandlerAdapter进行提取组装成网关上下文
  3. 然后网关的上下文会传递到DispatcherHandler,它负责将请求分发给RoutePredicateHandlerMapping
  4. RoutePredicateHandlerMapping负责路由查找,并根据路由断言判断路由是否可用
  5. 如果过断言成功,由FilteringWebHandler创建过滤器链并调用
  6. 请求会一次经过PreFilter--微服务--PostFilter的方法,最终返回响应
三、再gateway子项目中导入依赖
 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
        </dependency>

 

四、增加springboot配置文件,添加location和exam模块路由信息
server:
  port: 9999
spring:
  application:
    name: api-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      routes:
        - id: location
          uri: lb://demo-location
          predicates:
            - Path=/location/**
          filters:
            - StripPrefix=1       
        - id: exam
          uri: lb://demo-exam
          predicates:
            - Path=/exam/**
          filters:
            - StripPrefix=1

 

五、增加限流配置
限制为每秒只能请求一次~
0
六、验证路由和限流效果
确认服务注册:
0
验证路由转发,发现调用404:
 
0
查看gateway的说明文档,发现path和PrefixPath的区别,这个还真和以前的不一样,他的意思是带匹配路径转发:
path是带匹配路径转发请求,需要StripPrefix来截掉匹配模式不转发
PrefixPath是不转发匹配的模式
那我们试着改一下url再调用,官方文档诚不欺我:
 
0
那如果我们不想动原来的url怎么办呢,改yml呗,试一下:
 
0
 
0
但是还是跟大家保持一致,走gateway时多带一层吧,就不要用后面这种了。
验证限流,战术性连点,就出现下面限流的响应了:
0
posted on 2022-03-04 10:10  喃博思睿  阅读(117)  评论(0编辑  收藏  举报