spring cloud gateway全局过滤器 向request header中放数据

exchange.getRequest().getHeaders().set(); 是不能向 headers中放文件的

这时配置一个gateway全局过滤器  filter中 做了向 header放数据


@Component
public class AuthSignatureFilter implements GlobalFilter, Ordered {

    static Logger logger = LoggerFactory.getLogger(AuthSignatureFilter.class);

    /**
     * 全局过滤器 核心方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("request = {}",JSONArray.toJSONString( exchange.getRequest()) );
        String token = exchange.getRequest().getQueryParams().getFirst("authToken");
        //向headers中放文件,记得build
        ServerHttpRequest host = exchange.getRequest().mutate().header("a", "888").build();
        //将现在的request 变成 change对象 
        ServerWebExchange build = exchange.mutate().request(host).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return -200;
    }
}

这样发送给路由的request中就放了我们自定义的数据了

2019-11-19 更新

此方法在新版本中已经过时 使用新方法新方法

 Consumer httpHeaders = httpHeader -> {
            httpHeader.set("aaaa", "bbb");
            httpHeader.set("xxx", "cc");
            httpHeader.set("bbxx", "bbbx");
            httpHeader.set("aaaa", "bbb");
        };
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders).build();
        exchange.mutate().request(serverHttpRequest).build();

 

你可能感兴趣的:(java,spring,cloud,gateway)