protobuf
syntax = "proto3";
package com.example.grpc;
option java_multiple_files = true;
option java_package = "com.example.grpc";
option java_outer_classname = "HelloWorldProto";
service HelloWorld {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string greeting = 1;
}
$ protoc --java_out=./path/to/output/directory ./path/to/proto/file.proto
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
public class HelloWorldServer extends HelloWorldGrpc.HelloWorldImplBase {
public static void main(String[] args) throws Exception {
Server server = ServerBuilder.forPort(9090)
.addService(new HelloWorldServer())
.build();
server.start();
server.awaitTermination();
}
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
String greeting = "Hello, " + request.getName() + "!";
HelloResponse response = HelloResponse.newBuilder().setGreeting(greeting).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class HelloWorldClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
.usePlaintext()
.build();
HelloWorldGrpc.HelloWorldBlockingStub stub = HelloWorldGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder().setName("World").build();
HelloResponse response = stub.sayHello(request);
System.out.println(response.getGreeting());
channel.shutdown();
}
}
$ mvn compile
$ mvn exec:java -Dexec.mainClass="com.example.grpc.HelloWorldServer"
$ mvn exec:java -Dexec.mainClass="com.example.grpc.HelloWorldClient"
Hello, World!