springcloud之gateway自定义过滤器

springcloud gateway内置了19种过滤器工厂,我们可以根据不同的业务场景选择使用.当然,gateway也是支持实现自定义过滤器的.接下来,我们自定义一个filter用来统计每次请求的耗时.

相关依赖配置详见上一篇文章.

1.编写MyFilter

public class MyFilter implements GatewayFilter,Ordered {

    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //记录请求开始时间
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());

        return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
            @Override
            public void run() {
                Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                if (startTime != null) {
                    //打印
                    System.out.println(exchange.getRequest().getURI() + " 耗时" + (System.currentTimeMillis() - startTime));
                }
            }
        }));
    }

    @Override
    public int getOrder() {
        //filter执行的优先级,值越小则优先级越大
        return 0;
    }
}

2.将自定义filter注册到路由中

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator getRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes().
                route(new Function() {
                    @Override
                    public Route.AsyncBuilder apply(PredicateSpec predicateSpec) {
                        return predicateSpec
                                .path("/ribbon/**")
                                .filters(new Function() {
                                    @Override
                                    public UriSpec apply(GatewayFilterSpec gatewayFilterSpec) {
                                        return gatewayFilterSpec.stripPrefix(1).filter(new MyFilter());
                                    }
                                })
                                .uri("lb://RIBBON-CONSUMER")
                                .id("consumer9090)");

                    }
                }).build();
    }
}

3.启动路由工程16000,消费者9090,提供者8080和8081(集群)

访问http://localhost:16000/ribbon/helloConsumer

 

你可能感兴趣的:(springcloud)