Dropwizard and Protocol Buffers by example

霸气de小男生 提交于 2019-12-05 22:51:18
Paul Samsotha

You're right, it's not as easy as the one liner. You need to have protobuf generate code for it to work. Check out the Protocol Buffers Documentation. You first need to have a proto file that you compile with the protobuf compiler, which generates the code for you. This generated code is what you use to build your domain/model objects. The protobuf provider from Dropwizard works off this compiled code. Whether or not you use the Dropwizard provider, you well still need to use the generated code. See the section "How do I start" in the above link.

After you have the generated code, then in your resource method, the generated class/type is what you will need to return for the provider to be able to serialize it. You will also need to have @Produces("application/x-protobuf") or @Produces(ProtocolBufferMediaType.APPLICATION_PROTOBUF) on your resource method or resource class, so Jersey knows how to find the provider for the media type.

You can support both application/json and application/x-protobuf, as you can have more that one media type in the @Produces. Just use the syntax @Produces({ .. , .. }).

That's not all though. Since you will need to return two different types, i.e your simple POJO for JSON, or the generated type for Protobuf, you will either need to check for the header in the resource method

@Produces({"application/json", "application/x-protobuf"})
public Response getFoo(@Context HttpHeaders headers) {
    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    if (accepts.contains(MediaType.APPLICATION_JSON_TYPE) {
        return Response.ok(new Foo());
    } else if (accepts.contains(ProtocolBufferMediaType.APPLICATION_PROTOBUF_TYPE) {
        return Reponse.ok(new ProtoBufFoo());
    } else {
        // default
        return Response.ok(new Foo());
    }
}

Or you can have two different method, one for each type

@Produces("application/json")
public Response getFooJson() {
    return Response.ok(new Foo());
}

@Produces("application/x-protobuf")
public Response getFooProto() {
    return Response.ok(new ProtoBufFoo());
}

Whatever the client sends as its Accept header, that is the type that will be sent out. For example Accept: application/json or Accept: application/x-protobuf

See Also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!