赞
踩
实现需求:希望打印出方法运行的时间
filters:
- StripPrefix=1
- Time=true/false
1 注意代码中注释的地方
- package cn.haiwang.gatewayservice.filter;
-
- import lombok.Data;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.cloud.gateway.filter.GatewayFilter;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
- import java.net.URI;
- import java.util.Arrays;
- import java.util.List;
-
- /**
- * 开发自定义局部过滤器,显示方法运行的时间
- */
- /* 1 添加到Spring Bean中 */
- @Component
- @Slf4j
- /* 2 名称必须以GatewayFilterFactory结尾 */
- public class TimeGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeGatewayFilterFactory.PeizhiInfo> {
-
- /* 3 使用无参构造 */
- public TimeGatewayFilterFactory() {
- super(TimeGatewayFilterFactory.PeizhiInfo.class);
- }
-
- @Override
- public GatewayFilter apply(PeizhiInfo config) {
-
- return new GatewayFilter() {
- @Override
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- Boolean showTime = config.showTime;
- if(showTime!=null) {
- if (showTime.equals(false)) {
- return chain.filter(exchange);
- }
- }
-
- URI uri = exchange.getRequest().getURI();
- exchange.getAttributes().put("BEGIN_TIME",System.currentTimeMillis());
-
- return chain.filter(exchange).then(Mono.fromRunnable(()->{
- Long beginTime = exchange.getAttribute("BEGIN_TIME");
- if(beginTime!=null) {
- log.warn(uri+" 请示耗时 {} ms",System.currentTimeMillis() - beginTime);
- }
- }));
- }
- };
- }
-
- /*
- 60行 和 65行 名称要对应上
- */
- @Override
- public List<String> shortcutFieldOrder() {
- return Arrays.asList("showTime");
- }
-
- @Data
- protected static class PeizhiInfo {
- private Boolean showTime;
- }
- }
2 使用上面的过滤器
- spring:
- cloud:
- gateway:
- routes:
- - id: product_route
- uri: lb://product-service # lb指的是从nacos中按照名称获取微服务,并遵循负载均 衡策略
- predicates:
- - Path=/product-serv/**
- filters:
- - StripPrefix=1
- - Time=false # 使用自定义局部过滤器 ,不打印运行时间
- - id: order_route
- uri: lb://order-service # lb指的是从nacos中按照名称获取微服务,并遵循负载均 衡策略
- predicates:
- - Path=/order-serv/**
- filters:
- - StripPrefix=1
- - Time=true # 使用自定义局部过滤器 ,打印运行时间
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。