文章目录
Spring DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144
前言
最近在项目中遇到了两次org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144
。
问题1:REST API接口返回JSON超过256K时报错;
问题2:下载文件接口(返回二进制文件流,Content-Type为application/octet-stream
)文件超过256K时报错。
Spring版本:
- Spring Boot 2.2.2.RELEASE
- Spring Core 5.2.2.RELEASE
问题分析
项目基于Spring Cloud Gateway来开发了API网关,上面的错误都发生在API网关。
从日志来看是典型的缓冲区溢出错误。
对问题1,只要加大缓冲区,或者限制返回JSON的大小就可以解决。
对问题2,写文件流的方式,按道理写入缓冲区的数据会被消费走,不应该出现缓冲区溢出错误。
问题解决过程
通过配置参数加大缓冲区
默认的缓冲区为256K,可以通过配置spring.codec.max-in-memory-size
加大缓冲区:
spring:
codec:
max-in-memory-size: 2MB
关于该参数说明:
spring.codec.max-in-memory-size:
Limit on the number of bytes that can be buffered whenever the input stream needs to be aggregated. This applies only to the auto-configured WebFlux server and WebClient instances. By default this is not set, in which case individual codec defaults apply. Most codecs are limited to 256K by default.
不幸的是,该参数在Spring Boot 2.2.2.