java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringCloudGateway 过滤器

SpringCloudGateway 自定义局部过滤器场景分析

作者:sszdzq海怪

这篇文章主要介绍了SpringCloudGateway 自定义局部过滤器场景分析,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

场景:

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

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

到此这篇关于SpringCloudGateway 自定义局部过滤器的文章就介绍到这了,更多相关SpringCloudGateway 过滤器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文