Spring HttpMessageConverter
implementation with Alibaba FastJson and serializer/deserializer of Protobuf Messages.
With fastjson-protobuf
, we can use protocol buffers to define both request and response entities.
Only proto3 is supported for now.
dependencies {
compile "ai.ost:fastjson-protobuf:${VERSION}"
}
<dependency>
<groupId>ai.ost</groupId>
<artifactId>fastjson-protobuf</artifactId>
<version>${VERSION}</version>
</dependency>
First, define our own HttpMessageConverter
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters
) {
FastJsonProtobufHttpMessageConverter converter =
new FastJsonProtobufHttpMessageConverter();
converter.setSupportedMediaTypes(
Arrays.asList(
MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON_UTF8
)
);
converters.add(converter);
}
}
Then define Protocol Buffer messages:
message HelloRequest {
string name = 1;
}
message HelloResponse {
string msg = 1;
}
In order to use protobuf messages as entities, we can use gradle plugin com.google.protobuf
together with protoc and protoc plugin protoc-gen-grpc-java.
@RestController
public class APIController {
@RequestMapping(
value = "/hello",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@RequestBody
public HelloResponse hello(@RequestBody HelloRequest req) {
// We can use `HelloResponse` as the return value
return HelloResponse.newBuilder()
.setMsg("Hello " + req.getName())
.build();
}
}
$ curl -X POST -d '{"name": "World"}' http://localhost:8080/hello
{"msg": "Hello World"}
MIT