Spring Cloud Gateway ---GatewayFilter过滤器、过滤器工厂(入门)

前言


在一个系统中,经常需要对特定路由进行特定操作,而微服务中网关过滤器便起到了原来单体应用中过滤器作用,对请求进行处理,本文主要介绍Spring Cloud Gateway中过滤器的基本概念,以及入门使用。

概念


  • 1、Gateway中Filter生命周期只有两个阶段:pre和post
    pre:请求在路由之前被调用,我们可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等
    post:在路由到微服务以后执行。这种过滤器可用来为响应添加标准的HttpHeader、收集统计信息和指标、将响应从微服务发送给客户端等

  • 2、Spring Cloud GatewayFilter 分为两种:GatewayFilterGlobalFilterGlobalFilter 会应用到所有的路由上,而 GatewayFilter 将应用到单个路由或者一个分组的路由上。

GatewayFilter Factory

Spring Cloud Gateway中提供了很多自带的过滤器工厂使用。我们可以使用其完成各种操作。
例如:使用AddRequestParameter GatewayFilter Factory给特定请求添加参数(此处使用此方法的前提是网关已经注册到服务中心

在网关微服务中添加如下配置,对请求为Get方式的路由进行拦截添加参数foo=bar,并转发到uri中

#此处需要注意网关服务开启需要配置spring.cloud.gateway.discovery.locator.enabled: true
spring:
  cloud:
    gateway:
      routes:
      # =====================================
      - id: add_request_parameter_route
        uri: http://localhost:8003/provider/test
        filters:
        - AddRequestParameter=foo, bar
        predicates: 
        - Method=GET
复制代码

在provider微服务中添加http://localhost:8003/provider/test路由方法

@RestController
@RequestMapping("/provider")
public class TestController {
    @Value("${server.port}")
    private String addr;
    
    //此处需要参数名同为foo才能接受参数foo=bar
    @GetMapping("/test")
    public String test(String foo){
        String relstr= "来自服务提供者:"+addr+" foo:"+foo;
        return relstr;
    }
}
复制代码

启动网关服务(9001)和provider微服务(8003),以任意路由用Get方式请求网关,测试:如图可知访问成功且参数添加成功

AddRequestHeader GatewayFilter Factory

application.yml

spring:
  cloud:
    gateway:
      routes:
      # 为匹配路由请求添加请求头X-Request-Foo, Bar
      - id: add_request_header_route
        uri: http://example.org
        filters:
        - AddRequestHeader=X-Request-Foo, Bar
复制代码
AddResponseHeader GatewayFilter Factory

application.yml

spring:
   cloud:
     gateway:
       routes:
       # 为匹配路由请求添加响应头X-Response-Foo , Bar
       -  id:add_request_header_route
         uri:http://example.org
         过滤器:
         -  AddResponseHeader = X-Response-Foo , Bar
复制代码
Hystrix GatewayFilter Factory

application.yml

spring:
   cloud:
     gateway:
       routes:
       #
       -  id:hytstrix_route
         uri:http://example.org
         过滤器:
         -  Hystrix = myCommandName
复制代码
其他过滤器

参考官方文档

  • PrefixPath GatewayFilter Factory:uri添加前缀过滤器
  • RequestRateLimiter GatewayFilter Factory
  • RedirectTo GatewayFilter Factory

转载于:https://juejin.im/post/5c87a5e6f265da2dbf5f432c

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值