Skip to content

Latest commit

 

History

History
112 lines (89 loc) · 3.2 KB

README.md

File metadata and controls

112 lines (89 loc) · 3.2 KB

Build Status Coverage Maven Version

fastjson-protobuf

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.

Install

Gradle

dependencies {
  compile "ai.ost:fastjson-protobuf:${VERSION}"
}

Maven

<dependency>
  <groupId>ai.ost</groupId>
  <artifactId>fastjson-protobuf</artifactId>
  <version>${VERSION}</version>
</dependency>

Usage

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"}

License

MIT