zoukankan      html  css  js  c++  java
  • Spring Cloud Alibaba学习笔记(21)

    在前文中,我们介绍了Spring Cloud Gateway内置了一系列的全局过滤器,本文介绍如何自定义全局过滤器。

    自定义全局过滤需要实现GlobalFilter 接口,该接口和 GatewayFilter 有一样的方法定义,只不过 GlobalFilter 的实例会作用于所有的路由。

    自定义全局过滤器

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.cloud.gateway.filter.GatewayFilterChain;
    import org.springframework.cloud.gateway.filter.GlobalFilter;
    import org.springframework.stereotype.Component;
    import org.springframework.web.server.ServerWebExchange;
    import reactor.core.publisher.Mono;
    
    /**
     * 自定义全局过滤器
     */
    @Slf4j
    @Component
    public class CustomizeGlobalFilter implements GlobalFilter {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            String path = exchange.getRequest().getURI().getPath();
            log.info("[CustomizeGlobalFilter] 访问的接口:{}", path);
    
            long start = System.currentTimeMillis();
            return chain.filter(exchange)
                    // then的内容会在过滤器返回的时候执行,即最后执行
                    .then(Mono.fromRunnable(() ->
                            log.info("[ {} ] 接口的访问耗时:{} /ms", path, System.currentTimeMillis() - start)
                    ));
        }
    }
    

    上述代码中,我们使用@Component注解使该全局过滤器生效。还有一种方式,就是使用一个专门的配置类去实例化这些全局过滤器并交给Spring容器管理,代码如下:

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.cloud.gateway.filter.GlobalFilter;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.Ordered;
    import org.springframework.core.annotation.Order;
    
    @Slf4j
    @Configuration
    public class FilterConfig {
    
        @Bean
        // 该注解用于指定过滤器的执行顺序,数字越小越优先执行
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public GlobalFilter myGlobalFilter(){
            log.info("create myGlobalFilter...");
            return new MyGlobalFilter();
        }
    }
    
  • 相关阅读:
    file.delete()删除文件失败
    Axure RP Extension for Chrome插件离线安装
    C#---EF映射MySQL
    C#--二维数组
    MySQL--增删改查分页存储过程以及事务
    C# --MVC实现简单上传下载
    配置SQLServer,允许远程连接
    C#——工厂模式
    C#--条形码和二维码的简单实现
    C#—接口和抽象类的区别?
  • 原文地址:https://www.cnblogs.com/fx-blog/p/11753054.html
Copyright © 2011-2022 走看看