优化:网关堆外内存泄漏优化
This commit is contained in:
@@ -33,7 +33,7 @@ public class RequestResponseLoggingFilter implements GlobalFilter, Ordered {
|
||||
public static final String TRACE_ID_HEADER = "X-Trace-Id";
|
||||
|
||||
/** 最大记录的响应体长度(防止大 JSON) */
|
||||
private static final int MAX_BODY_LENGTH = 10 * 1024;
|
||||
private static final int MAX_BODY_LENGTH = 100 * 1024;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
@@ -123,23 +123,25 @@ public class RequestResponseLoggingFilter implements GlobalFilter, Ordered {
|
||||
if (!(body instanceof Flux)) {
|
||||
return super.writeWith(body);
|
||||
}
|
||||
|
||||
Flux<DataBuffer> fluxBody = (Flux<DataBuffer>) body;
|
||||
|
||||
return DataBufferUtils.join(fluxBody)
|
||||
.flatMap(joinedBuffer -> {
|
||||
byte[] content = null;
|
||||
try {
|
||||
int length = Math.min(
|
||||
joinedBuffer.readableByteCount(),
|
||||
MAX_BODY_LENGTH
|
||||
);
|
||||
content = new byte[length];
|
||||
joinedBuffer.read(content);
|
||||
// 先复制完整内容(不会影响 readerIndex)
|
||||
byte[] fullBytes = new byte[joinedBuffer.readableByteCount()];
|
||||
joinedBuffer.read(fullBytes);
|
||||
|
||||
logResponse(exchange, traceId, startTime, content);
|
||||
// 必须返回完整响应内容给客户端
|
||||
DataBuffer newBuffer = bufferFactory.wrap(
|
||||
joinedBuffer.asByteBuffer()
|
||||
);
|
||||
// 日志只截断读取
|
||||
int logLength = Math.min(fullBytes.length, MAX_BODY_LENGTH);
|
||||
byte[] logBytes = new byte[logLength];
|
||||
System.arraycopy(fullBytes, 0, logBytes, 0, logLength);
|
||||
|
||||
logResponse(exchange, traceId, startTime, logBytes);
|
||||
|
||||
// 用完整数据返回客户端
|
||||
DataBuffer newBuffer = bufferFactory.wrap(fullBytes);
|
||||
return super.writeWith(Mono.just(newBuffer));
|
||||
} finally {
|
||||
DataBufferUtils.release(joinedBuffer);
|
||||
|
||||
Reference in New Issue
Block a user