Currently I have a RESTful web service with endpoints that are exposed via Jersey/JAX-RS:
@Path("/widgets")
public class WidgetResource {
@GET
List<Widget> getAllWidgets() {
// gets Widgets somehow
}
@POST
Widget save(Widget w) {
// Save widget and return it
}
}
I use Jackson for serializing/deserializing my POJOs into JSON, and my service both responds to and sends back my POJOs as application/json
.
I am now looking to possibly use Google protocol buffers (or an equivalent technology) to help compress/optimize the communication between client and service, as JSON/text is pretty bulky/wasteful.
In reality, I have a large backend that consists of a "microservice" architecture; dozens of REST services communicating with each other; this is why I'm looking to optimize the the messages sent backk and forth between all of them.
So I ask: is it possible to still have Jersey/JAX-RS serve up my service endpoints, but to gut out the Jackson/JSON stuff and replace it with Google protocol buffers? If so, what might this code look like?
JAX-RS uses implementations of
MessageBodyReader
andMessageBodyWriter
to serialize/deserialize to and from differen media types. You can read more at JAX-RS Entity Providers. You can write your own the handle the serializion/derialization of your protobuf objects. Then just register the "provider(s)" with the application, either explicitly or implicitly through discovery.Example
widgets.proto
When this is compiled, I will be left with a
WidgetsProtoc
class with static innerWidget
andWidgetList
classes.WidgetResource
You'll notice the use of the
"application/protobuf"
media type. This isn't a standard media type, but there is a draft in the working. Also the Guava library has define this media type asMediaType.PROTOBUF
, which translates to"application/protobuf"
, so I chose to stick with that.MessageBodyReader
andMessageBodyWriter
all defined in one class. You can choose to do it separately. Makes no difference.TestCase
(Make sure the provider is registered both with the server and client)Result: