Skip to content

Commit 4d0800f

Browse files
zilong6bclozel
zilong6
authored andcommitted
Improve ContentCachingRequestWrapper performance
This commit improves the performance of `read` method variants to write to the cache in an optimized way. Issue: SPR-15762
1 parent 2ac6a15 commit 4d0800f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,57 @@ public ContentCachingInputStream(ServletInputStream is) {
213213
this.is = is;
214214
}
215215

216+
@Override
217+
public int readLine(final byte[] b, final int off, final int len) throws IOException {
218+
int count = is.readLine(b, off, len);
219+
cache(b, off, count);
220+
return count;
221+
}
222+
223+
private void cache(final byte[] b, final int off, final int count) {
224+
if (contentCacheLimit != null && cachedContent.size() == contentCacheLimit) {
225+
this.overflow = true;
226+
handleContentOverflow(contentCacheLimit);
227+
} else {
228+
int sizeToCache = contentCacheLimit == null || count + cachedContent.size() < contentCacheLimit
229+
? count
230+
: contentCacheLimit - cachedContent.size();
231+
cachedContent.write(b, off, sizeToCache);
232+
if (sizeToCache < count) {
233+
this.overflow = true;
234+
handleContentOverflow(contentCacheLimit);
235+
}
236+
}
237+
}
238+
239+
@Override
240+
public int read(final byte[] b) throws IOException {
241+
int count = super.read(b);
242+
if (!this.overflow && count > 0) {
243+
if (contentCacheLimit != null && cachedContent.size() == contentCacheLimit) {
244+
this.overflow = true;
245+
handleContentOverflow(contentCacheLimit);
246+
} else {
247+
int sizeToCache = contentCacheLimit == null || count + cachedContent.size() < contentCacheLimit
248+
? count
249+
: contentCacheLimit - cachedContent.size();
250+
cachedContent.write(b, 0, sizeToCache);
251+
if (sizeToCache < count) {
252+
this.overflow = true;
253+
handleContentOverflow(contentCacheLimit);
254+
}
255+
}
256+
}
257+
return count;
258+
}
259+
260+
@Override
261+
public int read(final byte[] b, final int off, final int len) throws IOException {
262+
int count = is.read(b, off, len);
263+
cache(b, off, count);
264+
return count;
265+
}
266+
216267
@Override
217268
public int read() throws IOException {
218269
int ch = this.is.read();

0 commit comments

Comments
 (0)