1、新建maven工程,pom.xml添加依賴和插件java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.study</groupId> <artifactId>grpc</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>grpc</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-all</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.Final</version> </extension> </extensions> <plugins> <!-- protobuf --> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <protocArtifact>com.google.protobuf:protoc:3.0.0-beta-2:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.14.0:exe:${os.detected.classifier}</pluginArtifact> <protoSourceRoot>src/main/proto</protoSourceRoot> <outputDirectory>${project.build.sourceDirectory}</outputDirectory> <!--設置是否在生成java文件以前清空outputDirectory的文件,默認值爲true,設置爲false時也會覆蓋同名文件 --> <clearOutputDirectory>false</clearOutputDirectory> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
2、新建源文件夾src/main/protoapache
在src/main/proto下新建test.proto類型文件maven
syntax = "proto3"; package grpc; option java_package = "com.study.grpc"; option java_outer_classname = "HelloWorldServiceProto"; option java_multiple_files = true; //服務端接口類 service Greeter { //服務端接口方法 rpc SayHello (HelloRequest) returns (HelloReply) {} } //請求參數 message HelloRequest { string name = 1; string sex = 2; } //響應參數 message HelloReply { string message = 1; }
3、執行maven命令ide
mvn compileui
刷新工程便可看到生成的類this
4、新建HelloWorldServer.javagoogle
package com.study.grpc; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; public class HelloWorldServer { private int port = 50051; private Server server; private void start() throws IOException { server = ServerBuilder.forPort(port).addService(GreeterGrpc.bindService(new GreeterImpl())).build().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(); } }); } 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(); } private class GreeterImpl implements GreeterGrpc.Greeter { public AtomicInteger count = new AtomicInteger(0); @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { System.out.println("call sayHello"); HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + request.getName() + request.getSex()) .build(); responseObserver.onNext(reply); responseObserver.onCompleted(); System.out.println(count.incrementAndGet() + Thread.currentThread().getName()); } } }
5、HelloWorldClient.javaatom
package com.study.grpc; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; public class HelloWorldClient { private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName()); 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) { logger.info("Will try to greet " + name + " ..."); HelloRequest request = HelloRequest.newBuilder().setName(name).setSex(" 女").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 { String user = "world"; if (args.length > 0) { user = args[0]; } client.greet(user); } finally { client.shutdown(); } } }
啓動HelloWorldServer,運行HelloWorldClient調用服務端,便可url
項目目錄結構以下:插件