Gateway系列---【过滤器工厂(GatewayFilter Factories又叫局部过滤器)---routes.filters的用法】

1.官网文档地址

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories

2.列举几个常用的用法

server:
  port: 8080
spring:
  application:
    name: fast-gateway
  cloud:
    gateway:
      routes:
          #如果接口报503,请检查pom中是否有spring-cloud-loadbalancer坐标
        - id: fast-auth
          # 网关转发地址,要和注册到nacos上的服务名一致
          uri: lb://fast-auth
          predicates:
            - Path=/fast-auth1/**  #匹配以 /fast-auth1 开头的请求
          filters:
            - StripPrefix=1 #去掉路径中的第一个部分,即 /fast-auth1
            - RewritePath=/(?<segment>.*), /fast-auth2/$\{segment} # StripPrefix=1去除了uri的第一层,将路径重写为带有 context-path 的路径
            - AddRequestHeader=X-Forwarded-Prefix,/fast-auth1 # 添加请求头,fast-auth的controller方法可以通过public String test(@RequestHeader("X-Forwarded-Prefix")String prefix)获取到该请求头的值
            - AddRequestParameter=color,red # 添加请求参数,fast-auth的controller方法可以通过public String test(@RequestParam("color")String color)获取到该请求参数的值
            - AddResponseHeader=X-Forwarded-Prefix,/fast-auth1 # 添加响应头
            - PrefixPath=/fast-auth # 添加context-path,需要转发到的服务需要配置一样的context-path
            - RedirectTo=302,https://www.baidu.com # 重定向到百度
            -
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos

3.自定义局部过滤器

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;

/**
 * 我们自定义的局部过滤器,要继承AbstractNameValueGatewayFilterFactory且我们定义的名称必须要以GatewayFilterFactory结尾并交给spring管理
 */
@Component
@Slf4j
public class CheckAuthGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain)->{
            log.info("调用CheckAuthGatewayFilterFactory自定义局部过滤器==="+config.getName()+":"+config.getValue());
            return chain.filter(exchange);
        };
    }
}

posted on   少年攻城狮  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-11-25 Mysql系列---【mysql中的数据类型和java中的数据类型的对应】
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示