Spring WebFlux With Protobuf

Protocol Buffers, in short Protobuf, are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data. You can take a look at this to learn more about this.

Spring WebFlux With Protobuf:

By default Spring Web/WebFlux modules use JSON for exchanging messages & the corresponding message converter. Spring also offers ProtobufHttpMessageConverter for us to use Protobuf if required.

Lets create a simple CRUD application with just GET and POST mappings to demo REST APIs using Spring WebFlux with Protobuf messages.

Sample Application:

We would create a simple Spring application is for managing persons with following dependencies.

Person Proto:

I define the Person proto as shown here.

syntax = "proto3";option java_multiple_files = true;
option java_package = "com.vinsguru.models";
message Person {
string name = 1;
int32 age = 2;
}

Person Repository:

I use a Map as a database in this example and I create a PersonRepository as shown here.

Person Controller:

Lets expose REST APIs for the Person type created using Protobuf.

That’s it! At this point, you can start your application which exposes REST API with Protobuf. (Do remember that Protobuf is NOT JSON or text format). You might not be able to test your APIs using browser as we do normally with JSON.

So I create a JUnit test and use WebClient to test the APIs as shown here.

Summary:

We were able successfully demonstrate Spring WebFlux with Protobuf. I am able to GET Person object and POST a protobuf Person object successfully. Spring also allows to have both JSON and Protobuf messages in a same application which is interesting!

The source code is available here.

Learn more about WebFlux:

Happy learning :)

--

--

Principal Software Engineer — passionate about software architectural design, microservices.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vinoth Selvaraj

Principal Software Engineer — passionate about software architectural design, microservices.