SpringCloudGateway 自定义局部过滤器

场景:

将所有请求转化为同一路径请求(方便穿网配置)在请求头内标识原来路径,然后在将请求分发给不同服务

复制代码
AllToOneGatewayFilterFactory
java 复制代码
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AllToOneGatewayFilterFactory extends AbstractGatewayFilterFactory<AllToOneGatewayFilterFactory.Config> {
    public AllToOneGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {

            ServerHttpRequest request = exchange.getRequest();
            request.getURI();
            // 替换路径
            String path = request.getPath().toString();
            ServerHttpRequest modifiedRequest = request.mutate().header(config.headerName, path).path(config.getToPath()).build();
            exchange = exchange.mutate().request(modifiedRequest).build();

            log.info("AllToOne: headers{{}:{}}, {} ---> {}", config.getHeaderName(),path, request.getURI(), modifiedRequest.getURI());

            return chain.filter(exchange);
        };
    }
    
    @Setter
    @Getter
    public static class Config {
        private String headerName;
        private String toPath;

    }
}
bash 复制代码
 spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true
      routes:
       - id: AllToOne_fnpt
         uri: http://localhost:19982
         predicates:
           - Path=/**
         filters:
           - name: AllToOne
             args:
               headerName: api-path
               toPath: /api/unified

注意:1.类名必须以GatewayFilterFactory结尾否则会出现不识别 的情况

2.配置的filters -name 的值为类的前缀(截取GatewayFilterFactory之后的)

相关推荐
SamDeepThinking1 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩4 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码6 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev7 小时前
Gson → kotlinx.serialization
android·java·kotlin
小bo波16 小时前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
咖啡八杯17 小时前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
SamDeepThinking1 天前
裁掉那个差程序员后,给你看团队里高手的代码:这个习惯,希望你有
java·后端·程序员
朕瞧着你甚好1 天前
技术雷达 & Java 集成评估报告 — Apache Tika 3.3.1
java·ai编程