今天主要介绍的是 在eclipse中 运用 protobuf + grpc 使用入门 一 中的新生成的 类来完成我们的grpc + java 的小 demo.网上有着 大量示例。但我想介绍的各个类由proto文件的生成关系。
总共生成了七个文件
option java_outer_classname = “HelloWorldProto”; ————》HelloWorldProto (生成的message类中会用到,具体之后再发表)
service Greeter ————》 Greeter,GreeterGrpc
message HelloRequest ————》HelloRequest,HelloRequestOrBuilder(HelloRequest implements HelloRequestOrBuilder)
message HelloReply ————》HelloReply,HelloReplyOrBuilder(HelloReply implements HelloReplyOrBuilder)
Server
public class HelloServer {
private int port = 50051;
private Server server;
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
System.out.println("service start...");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
HelloServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
// block 一直到退出程序
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final HelloServer server = new HelloServer();
server.start();
server.blockUntilShutdown();
}
// 实现 定义一个实现服务接口的类
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
System.out.println("service:"+req.getName());
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
Client
public class HelloClient {
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public HelloClient(String host,int port){
channel = ManagedChannelBuilder.forAddress(host,port)
.usePlaintext(true)
.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void greet(String name){
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response = blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
public static void main(String[] args) throws InterruptedException {
HelloClient client = new HelloClient("127.0.0.1",50051);
for(int i=0;i<5;i++){
client.greet("world:"+i);
}
}
server 成功图 这里报错是由于client在调用完成之后直接关闭了连接导致
以上windows 下的gprc+java demo 就全部完成了。