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之后的)

相关推荐
鱼宵7 小时前
Stream 终端操作一次讲透:collect、count、reduce 怎么选
java·stream·终端操作
白山编程大哥7 小时前
Java 后端如何优雅地把 List 集合返回给前端
java·前端·list
Linux运维技术栈7 小时前
CVE-2026-91403 高危漏洞修复:Rocky Linux 9 多版本 JDK 环境清理实操
java·linux·运维
On The Road :7 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
Shaoshing8 小时前
LeetCode100 49. 字母异位词分组
java·算法
划破黑暗的第一缕曙光9 小时前
[C++]:5.STL:string(2)
java·c++·redis
hhhjhl9 小时前
Undici 跨端三方库仓颉适配全流程
java·开发语言·ubuntu
wangchunyu1149 小时前
JAVA JVM内存结构与运行时数据区
java·开发语言·jvm
光锥智能9 小时前
海康机器人举行2026移动机器人新品发布会:箱式存拣升级,「明智」系列发布
java·前端·机器人
行思理10 小时前
Nginx 跨站请求(CORS)配置完全指南:从原理到生产实践
java·前端·nginx