gateway统计接口调用耗时情况设计思路(大厂面试题)
详情视频可以去看尚硅谷2024周阳老师的springCloud P86
知识出处自定义全局过滤器官网https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-combined-global-filter-and-gatewayfilter-ordering
这是springCloud里面的内容源码
@Bean
public GlobalFilter customFilter() {return new CustomGlobalFilter();
}public class CustomGlobalFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("custom global filter");return chain.filter(exchange);}@Overridepublic int getOrder() {return -1;}
}
`
@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {private static final String BEGIN_VISIT_TIME = "begin_visit_time";//开始访问时间/***第2版,各种统计* @param exchange* @param chain* @return*/@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {//先记录下访问接口的开始时间 exchange.getAttributes() 返回一个map容器 BEGIN_VISIT_TIME被记录到map里面exchange.getAttributes().put(BEGIN_VISIT_TIME, System.currentTimeMillis());return chain.filter(exchange).then(Mono.fromRunnable(()->{Long beginVisitTime = exchange.getAttribute(BEGIN_VISIT_TIME);if (beginVisitTime != null){log.info("访问接口主机: " + exchange.getRequest().getURI().getHost());log.info("访问接口端口: " + exchange.getRequest().getURI().getPort());log.info("访问接口URL: " + exchange.getRequest().getURI().getPath());log.info("访问接口URL参数: " + exchange.getRequest().getURI().getRawQuery());log.info("访问接口时长: " + (System.currentTimeMillis() - beginVisitTime) + "ms");log.info("我是美丽分割线: ###################################################");System.out.println();}}));}// 数字越小优先级越高@Overridepublic int getOrder() {return 0;}
}
调用结果
2024-03-09T13:40:55.305+08:00 INFO 5392 --- [cloud-gateway] [ main] com.atguigu.cloud.Main9527 : Started Main9527 in 2.484 seconds (process running for 2.94)
2024-03-09T13:41:03.492+08:00 INFO 5392 --- [cloud-gateway] [ctor-http-nio-5] com.atguigu.cloud.MyGlobalFilter : 访问接口主机: 192.168.127.117
2024-03-09T13:41:03.492+08:00 INFO 5392 --- [cloud-gateway] [ctor-http-nio-5] com.atguigu.cloud.MyGlobalFilter : 访问接口端口: 9527
2024-03-09T13:41:03.492+08:00 INFO 5392 --- [cloud-gateway] [ctor-http-nio-5] com.atguigu.cloud.MyGlobalFilter : 访问接口URL: /pay/gateway/get/1
2024-03-09T13:41:03.492+08:00 INFO 5392 --- [cloud-gateway] [ctor-http-nio-5] com.atguigu.cloud.MyGlobalFilter : 访问接口URL参数: null
2024-03-09T13:41:03.492+08:00 INFO 5392 --- [cloud-gateway] [ctor-http-nio-5] com.atguigu.cloud.MyGlobalFilter : 访问接口时长: 133ms
2024-03-09T13:41:03.492+08:00 INFO 5392 --- [cloud-gateway] [ctor-http-nio-5] com.atguigu.cloud.MyGlobalFilter : 我是美丽分割线: ###################################################