当前位置: 首页 > 文档资料 > SOP 中文文档 >

自定义过滤器

优质
小牛编辑
131浏览
2023-12-01

演示在网关追加一个header

public class CustomFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 演示在网关追加header
        ApiParam apiParam = ServerWebExchangeUtil.getApiParam(exchange);
        String token = apiParam.fetchAccessToken();
        ServerWebExchange serverWebExchange = ServerWebExchangeUtil.addHeaders(exchange, httpHeaders -> {
            httpHeaders.add("token", token);
        });
        return chain.filter(serverWebExchange);
    }

    @Override
    public int getOrder() {
        // 自定义过滤器可以从0开始
        return 0;
    }
}

使用过滤器,在sop-gateway中找到MyConfig,添加:

@Configuration
public class MyConfig {

    ...
    @Bean
    CustomFilter customFilter() {
        return new CustomFilter();
    }
    ...
}