I have a requirement to read and write compressed (GZIP) streams without intermediate storage. Currently, I'm using Spring RestTemplate
to do the writing, and Apache HTTP client to do the reading (see my answer here for an explanation of why RestTemplate
can't be used for reading large streams). The implementation is fairly straightforward, where I slap a GZIPInputStream
on the response InputStream
and move on.
Now, I'd like to switch to using Spring 5 WebClient (just because I'm not a fan of status quo). However, WebClient
is reactive in nature and deals with Flux<Stuff>
; I believe it's possible to get a Flux<DataBuffer>
, where DataBuffer is an abstraction over ByteBuffer
. Question is, how do I decompress it on the fly without having to store the full stream in memory (OutOfMemoryError
, I'm looking at you), or writing to local disk? It's worth mentioning that WebClient
uses Netty under the hood.
- Also see Reactor Netty issue-251.
- Also related to Spring integration issue-2300.
I'll admit to not knowing much about (de)compression, however, I did my research, but none of the material available online seemed particularly helpful.
compression on java nio direct buffers
Reading a GZIP file from a FileChannel (Java NIO)
Noting this here as it confused me a bit - the API has changed a bit as of 5.1.
I have a similar setup to the accepted answer for the
ChannelInboundHandler
:(The header values I needed are just hard-coded there for simplicity, otherwise it's identical.)
To register it however is different:
It seems Netty now maintains a user list of handlers separate from (and after) the system list, and
addHandlerFirst()
only puts your handler at the front of the user list. It therefore requires an explicit call toHttpContentDecompressor
to ensure it's definitely executed after your handler that inserts the correct headers.Then I create a
ClientHttpConnector
to use withWebClient
and inafterNettyContextInit
add the handler:This, of course, would fail for responses that are not GZIP compressed, so I use this instance of
WebClient
for a particular use case only, where I know for sure that the response is compressed.Writing is easy: Spring has a
ResourceEncoder
, soInputStream
can simply be converted toInputStreamResource
, and voila!