在前文中,咱们介绍了Spring Cloud Gateway内置了一系列的全局过滤器,本文介绍如何自定义全局过滤器。react
自定义全局过滤须要实现GlobalFilter 接口,该接口和 GatewayFilter 有同样的方法定义,只不过 GlobalFilter 的实例会做用于全部的路由。web
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容器管理,代码以下: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(); } }