eclipse-vertx / vertx-grpc

Development of the gRPC component for Eclipse Vert.x
Eclipse Public License 2.0
43 stars 23 forks source link

Support json wire format #108

Closed vietj closed 3 months ago

vietj commented 3 months ago

Support JSON wire format, documentation excerpts:


Vert.x gRPC Server

JSON wire format

gRPC implicitly assumes the usage of the Protobuf wire format.

The Vert.x gRPC server supports the JSON wire format as well.

You can use a JSON service method to bind a service method accepting requests carrying the application/grpc+json content-type.

server.callHandler(VertxGreeterGrpcServer.SayHello_JSON, request -> {
  request.last().onSuccess(helloRequest -> {
    request.response().end(HelloReply.newBuilder()
      .setMessage("Hello " + helloRequest.getName()).build()
    );
  });
});

NOTE: JSON encoding/decoding is achieved by com.google.protobuf:protobuf-java-util library.

Anemic JSON is also supported with Vert.x JsonObject

ServiceMethod<JsonObject, JsonObject> sayHello = ServiceMethod.server(
  ServiceName.create("helloworld", "Greeter"),
  "SayHello",
  GrpcMessageEncoder.JSON_OBJECT,
  GrpcMessageDecoder.JSON_OBJECT
);

server.callHandler(sayHello, request -> {
  request.last().onSuccess(helloRequest -> {
    request.response().end(new JsonObject().put("message", "Hello " + helloRequest.getString("name")));
  });
});

Vert.x gRPC Client

JSON wire format

gRPC implicitly assumes the usage of the Protobuf wire format.

The Vert.x gRPC client supports the JSON wire format as well.

You can call a JSON service method accepting requests carrying the application/grpc+json content-type.

client
  .request(server, VertxGreeterGrpcClient.SayHello_JSON).compose(request -> {
    request.end(HelloRequest
      .newBuilder()
      .setName("Bob")
      .build());
    return request.response().compose(response -> response.last());
  }).onSuccess(reply -> {
    System.out.println("Received " + reply.getMessage());
  });

NOTE: JSON encoding/decoding is achieved by com.google.protobuf:protobuf-java-util library.

Anemic JSON is also supported with Vert.x JsonObject

ServiceMethod<JsonObject, JsonObject> sayHello = ServiceMethod.client(
  ServiceName.create("helloworld", "Greeter"),
  "SayHello",
  GrpcMessageEncoder.JSON_OBJECT,
  GrpcMessageDecoder.JSON_OBJECT
);
client
  .request(server, sayHello).compose(request -> {
    request.end(new JsonObject().put("name", "Bob"));
    return request.response().compose(response -> response.last());
  }).onSuccess(reply -> {
    System.out.println("Received " + reply.getString("message"));
  });