dependencies {
implementation 'io.grpc:grpc-core:1.42.0'
}
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.example.grpc";
option java_outer_classname = "ExampleServiceProto";
service ExampleService {
rpc ExampleMethod(RequestType) returns (ResponseType);
}
message RequestType {
string requestMessage = 1;
}
message ResponseType {
string responseMessage = 1;
}
protoc -Isrc/main/proto --java_out=src/main/java src/main/proto/example.proto
package com.example.grpc;
import io.grpc.stub.StreamObserver;
public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase {
@Override
public void exampleMethod(RequestType request, StreamObserver<ResponseType> responseObserver) {
String requestMessage = request.getRequestMessage();
String responseMessage = "Response: " + requestMessage;
ResponseType response = ResponseType.newBuilder()
.setResponseMessage(responseMessage)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
package com.example.grpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class GrpcServer {
private static final int PORT = 50051;
private Server server;
public static void main(String[] args) throws IOException, InterruptedException {
GrpcServer grpcServer = new GrpcServer();
grpcServer.start();
grpcServer.blockUntilShutdown();
}
private void start() throws IOException {
server = ServerBuilder.forPort(PORT)
.addService(new ExampleServiceImpl())
.build()
.start();
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
}
package com.example.grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
private static final String HOST = "localhost";
private static final int PORT = 50051;
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT)
.usePlaintext()
.build();
ExampleServiceGrpc.ExampleServiceBlockingStub blockingStub = ExampleServiceGrpc.newBlockingStub(channel);
RequestType request = RequestType.newBuilder()
.setRequestMessage("Hello GRPC!")
.build();
ResponseType response = blockingStub.exampleMethod(request);
System.out.println("Response: " + response.getResponseMessage());
channel.shutdown();
}
}