Java中使用GRPC
Posted areful
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中使用GRPC相关的知识,希望对你有一定的参考价值。
0.编写.proto文件:
syntax = "proto3"; option java_multiple_files = true; option java_package = "io.grpc.examples.helloworld"; option java_outer_classname = "HelloWorldProto"; option objc_class_prefix = "HLW"; package helloworld; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
1.编译.proto生成对应Java源文件:
protoc --grpc_out=..\java --plugin=protoc-gen-grpc=D:\Dev\protoc\protoc-gen-grpc-java-1.9.1-windows-x86_64.exe helloworld.proto
2.编写Server端代码:
package io.grpc.examples.helloworld; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class HelloWorldServer { private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName()); private Server server; private void start() throws IOException { int port = 50051; server = ServerBuilder.forPort(port) .addService(new GreeterImpl()) .build() .start(); logger.info("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread(() -> { 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(); } } private void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination(); } } public static void main(String[] args) throws IOException, InterruptedException { final HelloWorldServer server = new HelloWorldServer(); server.start(); server.blockUntilShutdown(); } static class GreeterImpl extends GreeterGrpc.GreeterImplBase { @Override public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { String name = req.getName(); logger.log(Level.INFO, "Received name: " + name); HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + name).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } }
3.编写Client端代码:
package io.grpc.examples.helloworld; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; public class HelloWorldClient { private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName()); private final ManagedChannel channel; private final GreeterGrpc.GreeterBlockingStub blockingStub; private HelloWorldClient(String host, int port) { this(ManagedChannelBuilder.forAddress(host, port) // needing certificates. .usePlaintext() .build()); } private HelloWorldClient(ManagedChannel channel) { this.channel = channel; blockingStub = GreeterGrpc.newBlockingStub(channel); } private void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } private void greet(String name) { logger.info("Will try to greet " + name + " ..."); HelloRequest request = HelloRequest.newBuilder().setName(name).build(); HelloReply response; try { response = blockingStub.sayHello(request); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } logger.info("Greeting: " + response.getMessage()); } public static void main(String[] args) throws Exception { HelloWorldClient client = new HelloWorldClient("localhost", 50051); try { for(int i=0; i<10; i++){ String user = "World!"; if (args.length > 0) { user = args[0]; /* Use the arg as the name to greet if provided */ } client.greet(user); Thread.sleep(3000); } } finally { client.shutdown(); } } }
4.分别运行Server、Client代码。
以上是关于Java中使用GRPC的主要内容,如果未能解决你的问题,请参考以下文章
grpc proto文件生成java.net实体类以及客户端代码
如何为 gRPC 生成的 Java 代码实现 com.google.protobuf.BlockingRpcChannel?