spring_cloud之网关(Gateway 过滤器)

一、简介

  

  官网链接:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.1.RELEASE/single/spring-cloud-gateway.html#_gatewayfilter_factories

  用法:

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5           # 路由Id
 6         - id: springcloud-eureka-provider-routes
 7           #代理服务器地址
 8           uri: lb://springcloud-eureka-provider
 9           #断言规则
10           predicates:
11             #- Path=/**
12             - Path=/api/provider/**
13           filters:
14             #配置添加前缀
15             #- PrefixPath=/provider
16           #配置去除前缀 1:标识1个路径 2:标识2个路径 以此类推
17             - StripPrefix=1
18       # 添加默认过滤器, 对所有路由都生效
19       default-filters:
20         - AddResponseHeader=X-Response-Foo, Bar

 

  过滤器类型:

    1、局部过滤器:通过spring.application.cloud.gateway.routes.filters配置在具体路由下,只作用在当前路由上

    2、全局过滤器:通过spring.application.cloud.gateway.default-filters配置 这些过滤器实现GatewayFilterFactory接口,全局过滤器不需要在配置文件中配置,实现GlobalFilter接口即可。

  使用场景

    请求鉴权:一般GatewayFilterchain执行filter方法前,如果发现没有访问权限,直接就返回空。

    异常处理:一般GatewayFilterchain执行filter方法后,记录异常并返回。

    服务调用时长统计:GatewayFilterchain执行filter方法前后根据时间统计。

二、自定义局部过滤器

三、自定义全局过滤器

 

posted @ 2023-03-04 20:48  爱,诗意永存  阅读(359)  评论(0编辑  收藏  举报