|
|
@@ -1,42 +1,56 @@
|
|
|
package com.jzg.filter;
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
-import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
|
|
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
|
|
-import org.springframework.context.ApplicationContext;
|
|
|
+import org.springframework.core.Ordered;
|
|
|
import org.springframework.core.annotation.Order;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
import org.springframework.web.server.ServerWebExchange;
|
|
|
import reactor.core.publisher.Mono;
|
|
|
|
|
|
-import java.time.Duration;
|
|
|
-import java.time.Instant;
|
|
|
-
|
|
|
+/**
|
|
|
+ * 统计每个请求在整个服务器端耗时多久(毫秒级别)
|
|
|
+ *
|
|
|
+ * @author lipf
|
|
|
+ * @date 2026/4/2 11:44
|
|
|
+ */
|
|
|
@Component
|
|
|
-@Order(0)
|
|
|
+@Order(Ordered.HIGHEST_PRECEDENCE)
|
|
|
@Slf4j
|
|
|
public class AuthFilter implements GlobalFilter {
|
|
|
|
|
|
- @Autowired
|
|
|
- private ApplicationContext applicationContext;
|
|
|
+ // 定义一个 Key,用于在 Exchange 属性中暂存开始时间
|
|
|
+ private static final String BEGIN_VISIT_TIME = "begin_visit_time";
|
|
|
|
|
|
+ /**
|
|
|
+ * 统计每个请求在整个服务器端耗时多久(毫秒级别)
|
|
|
+ *
|
|
|
+ * @author lipf, modify by lipf
|
|
|
+ * @date 2026/4/2 11:43
|
|
|
+ */
|
|
|
@Override
|
|
|
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
|
|
+ // 1. 【Pre 阶段】请求刚进来,记录当前时间戳
|
|
|
+ exchange.getAttributes().put(BEGIN_VISIT_TIME, System.currentTimeMillis());
|
|
|
// 获取请求路径和方法
|
|
|
String path = exchange.getRequest().getPath().value();
|
|
|
-
|
|
|
return chain.filter(exchange)
|
|
|
.doOnSuccess(v -> {
|
|
|
- long cost = Duration.between(Instant.now(), Instant.now()).toMillis();
|
|
|
- int statusCode = exchange.getResponse().getStatusCode().value();
|
|
|
- log.info("【Gateway响应出口】 请求地址:{} , 耗时: {}ms , 状态码: {} ", path, statusCode, cost);
|
|
|
+ // 【Post 阶段】响应回来,计算耗时
|
|
|
+ Long beginTimeObj = exchange.getAttribute(BEGIN_VISIT_TIME);
|
|
|
+ long beginTime = beginTimeObj != null ? beginTimeObj : System.currentTimeMillis();
|
|
|
+
|
|
|
+ long cost = System.currentTimeMillis() - beginTime;
|
|
|
+ int statusCode = exchange.getResponse().getStatusCode() != null ? exchange.getResponse().getStatusCode().value() : -1;
|
|
|
+ log.info("【Gateway响应出口】 请求地址:{} , 耗时: {}ms , 状态码: {} ", path, cost, statusCode);
|
|
|
})
|
|
|
- // 发生异常时记录日志(ERROR级别)
|
|
|
.doOnError(e -> {
|
|
|
- long cost = Duration.between(Instant.now(), Instant.now()).toMillis();
|
|
|
+ // 【Post 阶段】响应回来,计算耗时
|
|
|
+ Long beginTimeObj = exchange.getAttribute(BEGIN_VISIT_TIME);
|
|
|
+ long beginTime = beginTimeObj != null ? beginTimeObj : System.currentTimeMillis();
|
|
|
+ long cost = System.currentTimeMillis() - beginTime;
|
|
|
log.error("【Gateway请求异常】 请求地址:{} , 耗时: {}ms, 异常信息",path,cost, e);
|
|
|
});
|
|
|
}
|
|
|
-
|
|
|
}
|