Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a custom HttpMessageConverter for the reactive Spring WebClient (Spring-WebFlux)

For the Spring org.springframework.web.client.RestTemplate, it was relatively easy to define an own HttpMessageConverter:

/**
 * Set the message body converters to use.
 * <p>These converters are used to convert from and to HTTP requests and responses.
 */
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    validateConverters(messageConverters);
    // Take getMessageConverters() List as-is when passed in here
    if (this.messageConverters != messageConverters) {
        this.messageConverters.clear();
        this.messageConverters.addAll(messageConverters);
    }
}

When converting my client to an reactive WebClient, I did not find a suitable way to define my own message converter as before with the RestTemplate.

Background: Our spring boot project is based on Scala and we use our own converter (based on com.fasterxml.jackson.module.scala.JacksonModule) to process Scala Case classes.

like image 494
user2314859 Avatar asked Feb 25 '20 12:02

user2314859


2 Answers

You can register custom codecs(Encoder, Decoder, HttpMessageReader, HttpMessageWriter) via WebClient.builder() for your WebClient in the reactive world.

  WebClient client = WebClient.builder()
                //see: https://github.com/jetty-project/jetty-reactive-httpclient
                //.clientConnector(new JettyClientHttpConnector())
                .clientConnector(new ReactorClientHttpConnector())
                .codecs(
                        clientCodecConfigurer ->{
                           // .defaultCodecs() set defaultCodecs for you
                           // clientCodecConfigurer.defaultCodecs();

                           //  You can customize an encoder based on the defualt config.
                           //  clientCodecConfigurer.defaultCodecs().jackson2Encoder(...)

                           // Or 
                           // use customCodecs to register Codecs from scratch.
                            clientCodecConfigurer.customCodecs().register(new Jackson2JsonDecoder());
                            clientCodecConfigurer.customCodecs().register(new Jackson2JsonEncoder());
                        }

                )
                .baseUrl("http://localhost:8080")
                .build();

like image 153
Hantsy Avatar answered Oct 18 '22 04:10

Hantsy


If you're using Spring Boot with WebFlux, you can add a CodecCustomizer bean, which you can use to register your own custom codecs:

@Bean
CodecCustomizer myCustomCodecCustomizer(...) {
    return configurer -> configurer.customCodecs().register(...);
}

By the way, when using Spring Boot with WebMVC, you can just add your HttpMessageConverter implementation as a bean and it will get picked up.

like image 1
Nils Breunese Avatar answered Oct 18 '22 04:10

Nils Breunese