!34 修复body数据过大超过默认256K时,报错(DataBufferLimitException: Exceeded limit on max bytes to buffer), 修改spring.codec.max-in-memory-size也无效的问题

Merge pull request !34 from 杨寒寒/hotfix/gateway-0522
This commit is contained in:
芋道源码 2023-05-28 15:58:27 +00:00 committed by Gitee
commit 5dd5bfb2c7
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F

View File

@ -9,6 +9,7 @@ import cn.iocoder.yudao.gateway.util.WebFrameworkUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
@ -23,7 +24,7 @@ import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.CodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
@ -31,7 +32,6 @@ import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
@ -57,7 +57,11 @@ import static cn.hutool.core.date.DatePattern.NORM_DATETIME_MS_FORMATTER;
@Component
public class AccessLogFilter implements GlobalFilter, Ordered {
private final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
/**
* 解决spring.codec.max-in-memory-size设置不生效的问题
*/
@Autowired
private CodecConfigurer codecConfigurer;
/**
* 打印日志
@ -137,7 +141,7 @@ public class AccessLogFilter implements GlobalFilter, Ordered {
*/
private Mono<Void> filterWithRequestBody(ServerWebExchange exchange, GatewayFilterChain chain, AccessLog gatewayLog) {
// 设置 Request Body 读取时设置到网关日志
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
ServerRequest serverRequest = ServerRequest.create(exchange, codecConfigurer.getReaders());
Mono<String> modifiedBody = serverRequest.bodyToMono(String.class).flatMap(body -> {
gatewayLog.setRequestBody(body);
return Mono.just(body);