How to consume a large response using Spring WebClient?

Spring WebClient is a new library provided by Spring to call REST services.

It can be used to call rest services in an asynchronous way.

Spring team is planning to retire RestTemplate and so it is better to start using Spring WebClients in your projects even for synchronous calls.

And if you do use Spring WebClient , you may run into issues when your are invoking a REST service which returns a huge response.

For example ,

Consider this REST API:

Notice that the response returned by the API is big (almost 10 MB).

Calling the above REST service using traditional Spring REST Template will not throw any error. You can retrieve the entire response.

But if you use WebClient you will get an exception!

For example , consider the below WebClient rest client code:


	 Mono<Map> response = WebClient.builder().build()
.get().uri("http://localhost:8080/getLargeResponse")
.retrieve().bodyToMono(Map.class);

	


If you execute the above code , you will get the below error:

This is because the default buffer size used by Spring WebClient is 262144 bytes (256 KB)

To resolve this issue , you need to increase the buffer size.

This can be done using the below code:

Mono<Map> response = WebClient
				.builder()
				.exchangeStrategies(
						ExchangeStrategies.builder().codecs(

								configurer -> configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)).build()

								)

				.build()
				.get()
				.uri("http://localhost:8080/getLargeResponse")
				.retrieve()
				.bodyToMono(Map.class);

You can increase the buffer size by customizing the default codecs set up.

Below line does it:

	.exchangeStrategies(
						ExchangeStrategies.builder().codecs(

								configurer -> configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)).build()

								)

I have set it to 10 MB.

And then it works.


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading