How to configure HTTP Service Clients with Protobuf in Spring Boot 4?

1 week ago 10
ARTICLE AD BOX

In the HTTP interface, declare that you want to send and receive protobuf:

import static org.springframework.http.MediaType.APPLICATION_PROTOBUF_VALUE; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.service.annotation.PutExchange; public interface SomeBackendApi { @PutExchange( value = "/endpoint", contentType = APPLICATION_PROTOBUF_VALUE, accept = APPLICATION_PROTOBUF_VALUE) ProtobufResponseObject doSomething(@RequestBody ProtobufRequestObject request); }

Create a configuration class where you configure the ProtobufHttpMessageConverter for the http client:

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.web.client.support.RestClientHttpServiceGroupConfigurer; import org.springframework.web.service.registry.ImportHttpServices; @Configuration(proxyBeanMethods = false) @ImportHttpServices(group = "some-backend", types = SomeBackendApi.class) public class SomeBackendConfiguration { @Bean public RestClientHttpServiceGroupConfigurer groupConfigurer() { return groups -> groups .filterByName("some-backend") .forEachClient( (group, clientBuilder) -> clientBuilder.configureMessageConverters( it -> it.addCustomConverter(new ProtobufHttpMessageConverter()))); } }

You can now inject an instance of SomeBackendApi into any other Spring bean and call its method(s) to do a remote call using Protobuf.

Wim Deblauwe's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article