service MyService {
rpc sayHello (HelloRequest) returns (HelloResponse);
}
class MyServiceImpl extends MyServiceGrpc.MyServiceImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
String message = "Hello, " + request.getName() + "!";
HelloResponse response = HelloResponse.newBuilder().setMessage(message).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
Server server = ServerBuilder.forPort(50051)
.addService(new MyServiceImpl())
.build();
server.start();
server.awaitTermination();
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
.usePlaintext()
.build();
MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder().setName("John").build();
HelloResponse response = stub.sayHello(request);
System.out.println(response.getMessage());
plugins {
id "com.google.protobuf" version "0.8.14"
id "grpc" version "0.8.14"
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
grpc {
java {
grpcVersion = "${grpcVersion}"
}
}
dependencies {
protobuf 'com.google.protobuf:protobuf-java:{protobufVersion}'
implementation 'io.grpc:grpc-netty:{grpcVersion}'
protobuf 'io.grpc:grpc-protobuf:{grpcVersion}'
protobuf 'com.google.protobuf:protobuf-java-util:{protobufVersion}'
}