zoukankan      html  css  js  c++  java
  • gateway(二、过滤器)

    过滤器其实是路由转发+过滤器  

    自定义过滤器

    首先创建一个类继承下边两个类,实现过滤器

    然后在启动项中通过创建bean的方式创建路由器 

    @Component
    public class TimeFilter implements GatewayFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(TimeFilter.class);

    private static final String ELAPSED_TIME_BEGIN = "timeBegin";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    exchange.getAttributes().put(ELAPSED_TIME_BEGIN, System.currentTimeMillis());
    return chain.filter(exchange).then(
    Mono.fromRunnable(() -> {
    Long startTime = exchange.getAttribute(ELAPSED_TIME_BEGIN);
    if (startTime != null) {
    logger.info(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
    }
    })
    );
    }

    @Override
    public int getOrder() {
    return Ordered.LOWEST_PRECEDENCE;
    }
    }
     @Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
    // @formatter:off
    return builder.routes()
    // .route(r -> r.path("/consulserver/**")
    // .filters(f -> f.stripPrefix(1)
    // .filter(new TimeFilter())
    // .addResponseHeader("X-Response-Default-Foo", "Default-Bar"))
    // .uri("lb://consulserver")
    // .order(0)
    // .id("fluent_customer_service")
    // )
    // .build();


    全局过滤器只需要把继承的类改变一下就行了
    之后在启动项中创建这个类的bean就行了
    public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

    String token = exchange.getRequest().getQueryParams().getFirst("token");
    if (token == null||token.isEmpty()){
    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
    return exchange.getResponse().setComplete();
    }
    return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
    return 0;
    }
    }
    在启动类中创建
    //    @Bean
    // public TokenFilter tokenFilter(){
    // return new TokenFilter();
    // }
  • 相关阅读:
    Java(类与对象)
    Java(数组)动手动脑
    《大道至简》第一章阅读笔记
    Java(接口与继承)动手动脑
    《大道至简》第二章阅读笔记
    Java(String)
    Java动手动脑
    Java程序设计笔记
    控制结构(1)判断控制
    MySQL Cluster 详细配置文件(config.ini)
  • 原文地址:https://www.cnblogs.com/tflike/p/10044778.html
Copyright © 2011-2022 走看看