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();
        }
    }
    
  • 相关阅读:
    SharePoint 2010 产品六大功能模块
    转:USB主机控制器(Host Controller)--深入理解
    转:C#基础知识梳理
    SharePoint 2010 Logging Improvements
    列表不能在数据表视图中显示
    selenium driver.close()与driver.quit()区别
    启动远程主机上的项目
    linux命令:passwd修改用户密码
    no crontab for root
    10位和13位时间戳转换成时间字符串
  • 原文地址:https://www.cnblogs.com/fx-blog/p/11753054.html
Copyright © 2011-2022 走看看