gRPC HelloWorld java版
1. 建立一個maven專案 2. 加入依賴 3. 編寫proto檔案 4. 編寫服務端檔案, 和客戶端檔案 package org; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.examples.helloworld.GreeterGrpc; import io.grpc.examples.helloworld.HelloReply; import io.grpc.examples.helloworld.HelloRequest; import io.grpc.stub.StreamObserver; import java.io.IOException; /** * * Created by saxing on 2018/5/30. */ public class HelloWorldServer { private int port = 23333; 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"); HelloWorldServer.this.stop(); System.err.println("*** server shut down"); } }); } private void stop(){ if (server != null){ server.shutdown(); } } public static void main(String[] args) throws InterruptedException, IOException { final HelloWorldServer server = new HelloWorldServer(); server.start(); server.blockUtilShutdown(); } private void blockUtilShutdown() throws InterruptedException{ if (server != null){ server.awaitTermination(); } } private class GreeterImpl extends GreeterGrpc.GreeterImplBase{ @Override public void sayHello(HelloRequest req, StreamObserver responseObserver){ System.out.println("service: " + req.getName()); HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } } package org; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.examples.helloworld.GreeterGrpc; import io.grpc.examples.helloworld.HelloReply; import io.grpc.examples.helloworld.HelloRequest; import java.util.concurrent.TimeUnit; /** * * Created by saxing on 2018/5/30. */ public class HelloWorldClient { private final ManagedChannel channel; private final GreeterGrpc.GreeterBlockingStub blockingStub; public HelloWorldClient(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 { HelloWorldClient client = new HelloWorldClient("127.0.0.1", 23333); for (int i = 0; i < 5; i++) { client.greet("world: " + i); } client.shutdown(); } } 5. 執行測試結果 更多詳細參考: https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples --------------------- 本文來自 颯行 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/u011389515/article/details/80511255?utm_source=copy