protobuf
syntax = "proto3";
package com.example;
service HelloWorldService {
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
shell
protoc --java_out=./src/main/java hello.proto
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
public class HelloWorldServer {
public static void main(String[] args) throws Exception {
Server server = ServerBuilder.forPort(8080)
.addService(new HelloWorldServiceImpl())
.build();
server.start();
server.awaitTermination();
}
static class HelloWorldServiceImpl extends HelloWorldServiceGrpc.HelloWorldServiceImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
String name = request.getName();
String message = "Hello, " + name + "!";
HelloResponse response = HelloResponse.newBuilder()
.setMessage(message)
.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", 8080)
.usePlaintext()
.build();
HelloWorldServiceGrpc.HelloWorldServiceBlockingStub stub = HelloWorldServiceGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder()
.setName("John")
.build();
HelloResponse response = stub.sayHello(request);
System.out.println(response.getMessage());
channel.shutdown();
}
}