protobuf
syntax = "proto3";
package com.example.userservice;
service UserService {
rpc GetUser(UserRequest) returns (UserResponse) {}
}
message UserRequest {
string userId = 1;
}
message UserResponse {
string name = 1;
int32 age = 2;
}
bash
$ protoc --java_out=./src/main/java user_service.proto
package com.example.userservice;
import io.grpc.stub.StreamObserver;
public class UserServiceImpl extends UserServiceGrpc.UserServiceImplBase {
@Override
public void getUser(UserRequest request, StreamObserver<UserResponse> responseObserver) {
UserResponse response = UserResponse.newBuilder()
.setName("John Doe")
.setAge(30)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
package com.example.userservice;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class GRPCServer {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(9090)
.addService(new UserServiceImpl())
.build();
server.start();
server.awaitTermination();
}
}