1. 程式人生 > >GRPC 配置、使用、安裝文件 java-windows-eclipse

GRPC 配置、使用、安裝文件 java-windows-eclipse

2.新建maven專案,將.proto放入src/main/proto資料夾下面 3、編寫pom.xml檔案,引入外掛
<projectxmlns="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.ytf.simple</groupId>
     <artifactId>protobuf</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>simple</name>
     <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
           <grpc.version>1.0.1</grpc.version>
     </properties>
     <dependencies>
           <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-netty</artifactId>
                <version>1.0.1</version>
           </dependency>
           <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-protobuf</artifactId>
                <version>1.0.1</version>
           </dependency>
           <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-stub</artifactId>
                <version>1.0.1</version>
           </dependency>
           <dependency>
                <groupId>com.google.protobuf</groupId>
                <artifactId>protobuf-java</artifactId>
                <version>3.1.0</version>
           </dependency>
           <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-core</artifactId>
                <version>${grpc.version}</version>
           </dependency>
           <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-all</artifactId>
                <version>1.0.1</version>
           </dependency>
           <!-- <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId>
                <version>${grpc.version}</version> </dependency> <dependency> <groupId>com.orbitz.consul</groupId>
                <artifactId>consul-client</artifactId> <version>0.10.0</version> </dependency> -->
     </dependencies>
     <build>
           <finalName>com.ytf.rpc.demo</finalName>
           <extensions>
                <extension>
                     <groupId>kr.motd.maven</groupId>
                     <artifactId>os-maven-plugin</artifactId>
                     <version>1.5.0.Final</version>
                </extension>
           </extensions>
           <plugins>
                <plugin>
                     <groupId>org.xolstice.maven.plugins</groupId>
                     <artifactId>protobuf-maven-plugin</artifactId>
                     <version>0.5.0</version>
                     <configuration>
                          <protocArtifact>com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}</protocArtifact>
                           <pluginId>grpc-java</pluginId>
                          <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.1:exe:${os.detected.classifier}</pluginArtifact>
                     </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>
                     <version>2.3.2</version>
                     <configuration>
                           <source>1.8</source>
                           <target>1.8</target>
                     </configuration>
                </plugin>
           </plugins>
     </build>
</project>



4、進入pom.xml的檔案目錄,開啟cmd視窗  (shift + 滑鼠右鍵 -->在此處開啟命令視窗)輸入
mvn compile


5、生成的java 以及grpc檔案目錄如下:
projectPath\target\generated-sources\protobuf\java
projectPath\Path\target\generated-sources\protobuf\grpc-java


6、將程式碼copy到專案src/main/java目錄下 重新整理專案即可 一、利用maven compile 來將proto生成java檔案
1.下載 protocol buffer 2/3 

    下載完成後,新增 window 環境變數(由於我本地有兩個版本,故我命名為protoc2/protoc3)新增完成後,進行驗證。如下圖:

    如果出現於作者同樣的圖,說明安裝成功!

2.在編譯的 gRPC 的時候 ,protocol buffer 需要將 protoc-gen-grpc-java 作為外掛來生成程式碼,

    文件介紹:http://www.grpc.io/docs/quickstart/java.html

    下載地址:https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/1.0.1/

    下載完成後,同樣的新增到 winddos環境變數中。

3.編寫 .proto 檔案 。命名為 : grpc-helloworld.proto .檔案內容如下:

syntax = "proto3"
; option java_generic_services = true; option java_multiple_files = true; option java_package = "com.hservice.grpc.schema"; option java_outer_classname = "HelloWorldProto"; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }

首先生成Proto 檔案

再執行生成命令:( >>>   protoc3 --plugin=protoc-gen-grpc-java=D:/sysEnv/protoc-gen-grpc-java.exe --grpc-java_out=java --proto_path=proto proto/g
rpc-helloworld.proto) 生成gRPC檔案

    如果在這一步的時候,執行失敗,請注意路徑引數的配置。

4.生成後,會在com.hservice.grpc.schema 包下生存 GreeterGrpc.java 檔案。我的生成後java 程式碼如下:

三、利用gradle build 來將proto生成java檔案

1、新建gradle3.0+++版本的gradle專案

2、編寫gradle.build檔案內容,如下: 3、進入gradle.build檔案所在目錄,,開啟cmd視窗 (shift + 滑鼠右鍵 -->在此處開啟命令視窗)輸入 gradle build 4、生成的檔案目錄如下: 然後複製過去就好 projectHome\build\generated\source\proto\main\java projectHome\build\generated\source\proto\main\grpc
applyplugin:'java'
applyplugin:'com.google.protobuf'
buildscript{
 repositories{
    mavenCentral()
  }
 dependencies{
   // ASSUMES GRADLE 2.12 OR HIGHER. Use plugin version 0.7.5 with earlier
   // gradle versions
    classpath'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
  }
}
repositories{
  mavenLocal()
  mavenCentral()
}
// IMPORTANT: You probably want the non-SNAPSHOT version of gRPC. Make sure you
// are looking at a tagged version of the example and not "master"!
// Feel free to delete the comment at the next line. It is just for safely
// updating the version in our release process.
defgrpcVersion ='1.0.1'// CURRENT_GRPC_VERSION
dependencies{
  compile"io.grpc:grpc-netty:${grpcVersion}"
  compile"io.grpc:grpc-protobuf:${grpcVersion}"
  compile"io.grpc:grpc-stub:${grpcVersion}"
  testCompile"junit:junit:4.11"
  testCompile"org.mockito:mockito-core:1.9.5"
}
protobuf {
  protoc {
    artifact ='com.google.protobuf:protoc:3.1.0'
  }
 plugins{
    grpc {
      artifact ="io.grpc:protoc-gen-grpc-java:${grpcVersion}"
    }
  }
  generateProtoTasks {
    all()*.plugins{
      grpc {
       // To generate deprecated interfaces and static bindService method,
       // turn the enable_deprecated option to true below:
        option'enable_deprecated=false'
      }
    }
  }
}
// Inform IntelliJ projects about the generated code.
applyplugin:'idea'
idea {
 module{
   // Not using generatedSourceDirs because of
   // https://discuss.gradle.org/t/support-for-intellij-2016/15294/8
    sourceDirs += file("${projectDir}/build/generated/source/proto/main/java");
    sourceDirs += file("${projectDir}/build/generated/source/proto/main/grpc");
  }
}
// Provide convenience executables for trying out the examples.
applyplugin:'application'
startScripts.enabled = false
taskrouteGuideServer(type: CreateStartScripts) {
  mainClassName ='io.grpc.examples.routeguide.RouteGuideServer'
  applicationName ='route-guide-server'
  outputDir =newFile(project.buildDir,'tmp')
  classpath = jar.outputs.files +project.configurations.runtime
}
taskrouteGuideClient(type: CreateStartScripts) {
  mainClassName ='io.grpc.examples.routeguide.RouteGuideClient'
  applicationName ='route-guide-client'
  outputDir =newFile(project.buildDir,'tmp')
  classpath = jar.outputs.files +project.configurations.runtime
}
taskhelloWorldServer(type: CreateStartScripts) {
  mainClassName ='io.grpc.examples.helloworld.HelloWorldServer'
  applicationName ='hello-world-server'
  outputDir =newFile(project.buildDir,'tmp')
  classpath = jar.outputs.files +project.configurations.runtime
}
taskhelloWorldClient(type: CreateStartScripts) {
  mainClassName ='io.grpc.examples.helloworld.HelloWorldClient'
  applicationName ='hello-world-client'
  outputDir =newFile(project.buildDir,'tmp')
  classpath = jar.outputs.files +project.configurations.runtime
}
taskcompressingHelloWorldClient(type: CreateStartScripts) {
  mainClassName ='io.grpc.examples.experimental.CompressingHelloWorldClient'
  applicationName ='compressing-hello-world-client'
  outputDir =newFile(project.buildDir,'tmp')
  classpath = jar.outputs.files +project.configurations.runtime
}
applicationDistribution.into('bin') {
  from(routeGuideServer)
  from(routeGuideClient)
  from(helloWorldServer)
  from(helloWorldClient)
  from(compressingHelloWorldClient)
  fileMode = 0755
}


四、編寫service 和 client for java
首先你得有:*Grpc.java,*Proto.java,*Builder.java檔案 1、編寫service,流 ①、繼承GreeterGrpc.GreeterImplBase 定義一個靜態內部類重寫你剛才定義的介面, 然後你還的有個start(),stop(),blockUntilShutdown()方法來操作服務端的開始停止,完整程式碼如下:
packagecom.ibm.crl.demo;
importjava.io.IOException;
importio.grpc.Server;
importio.grpc.ServerBuilder;
importio.grpc.stub.StreamObserver;
publicclassDemoServer {
   privateServerserver;
   /* The port on which the server should run */
   privateintport= 50051;
   privatevoidstart()throwsIOException {
       server= ServerBuilder.forPort(port).addService(newDemoGrpcImpl()).build().start();
        System.out.println("server start " +port);
        Runtime.getRuntime().addShutdownHook(newThread() {
           @Override
           publicvoidrun() {
               // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                DemoServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }
   privatevoidstop() {
       if(server!= null) {
           server.shutdown();
        }
    }
   /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
   privatevoidblockUntilShutdown()throwsInterruptedException {
       if(server!= null) {
           server.awaitTermination();
        }
    }
   /**
     * Main launches the server from the command line.
     */
   publicstaticvoidmain(String[]args)throwsIOException, InterruptedException {
       finalDemoServerserver = newDemoServer();
       server.start();
       server.blockUntilShutdown();
    }
   staticclassDemoGrpcImplextendsGreeterGrpc.GreeterImplBase {
       @Override
       publicStreamObserver<HelloRequest> sayHello(StreamObserver<HelloReply>responseObserver) {
           returnnewStreamObserver<HelloRequest>() {
               privateintcount= 0;
               publicvoidonNext(HelloRequestreq) {
                   try{
                        Thread.sleep(2000);
                    }catch(InterruptedExceptione) {
                       e.printStackTrace();
                    }
                   count++;
                    HelloReplyreply =
                            HelloReply.newBuilder().setMessage("demo " +req.getName()).build();
                   responseObserver.onNext(reply);
                    System.out.println("resquest:"+ req.getName() + System.currentTimeMillis());
                }
               publicvoidonError(Throwablet) {
                    System.err.println(System.currentTimeMillis() + " : "+ count
                            +"server demo error:"+ t.getMessage());
                   responseObserver.onError(t);
                }
               publicvoidonCompleted() {
                    System.out.println("task finish close session ! someone has died!"
                            + System.currentTimeMillis() +" times:"+ count);
                   responseObserver.onCompleted();
                }
            };
        }
    }
}
// end


2、編寫client,流 主要是初始化channel和GreeterStub程式碼如下:
packagecom.ibm.crl.demo;
importjava.util.concurrent.CountDownLatch;
importjava.util.concurrent.TimeUnit;
importio.grpc.ManagedChannel;
importio.grpc.ManagedChannelBuilder;
importio.grpc.examples.helloworld.HelloWorldServer;
importio.grpc.stub.StreamObserver;
/**
 * A simple client that requests a greeting from the{@link HelloWorldServer}.
 */
publicclassDemoClient {
   privatefinalManagedChannelchannel;
   privatefinalGreeterGrpc.GreeterStubstub;
   privateintcount= 1;
   /** Construct client connecting to HelloWorld server at {@code host:port}. */
   publicDemoClient(Stringhost,intport) {
       this(ManagedChannelBuilder.forAddress(host,port).usePlaintext(true));
    }
   /** Construct client for accessing RouteGuide server using the existing channel. */
    DemoClient(ManagedChannelBuilder<?>channelBuilder) {
       channel= channelBuilder.build();
        stub= GreeterGrpc.newStub(channel);

    }
   publicvoidshutdown()throwsInterruptedException {
       channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }
   /** Say hello to server. */
   publicvoidgreet(Stringname) {
       try{
           finalCountDownLatchfinishLatch = newCountDownLatch(1);
            StreamObserver<HelloRequest>ob =stub.sayHello(newStreamObserver<HelloReply>() {
               @Override
               publicvoidonNext(HelloReplyvalue) {
                    System.out.println("response:"+ value.getMessage() + count);
                   count++;
                }
               publicvoidonError(Throwablet) {
                    System.err.println("client demo error:" +t.getMessage());
                   finishLatch.countDown();
                }
               publicvoidonCompleted() {
                    System.out.println("finished demo");
                   finishLatch.countDown();
                }
            });
            Thread.sleep(400);
            HelloRequestreply = HelloRequest.newBuilder().setName(name).build();
            System.out.println(System.currentTimeMillis());
           for(inti= 0; i< 1; i++) {
               ob.onNext(reply);
            }
           ob.onCompleted();
        }catch(Exceptione) {
           e.printStackTrace();
        }
    }
   /**
     * Greet server. If provided, the first element of {@code args} is the name to use in the
     * greeting. 客戶端如果5秒沒收到響應,則斷開連線。
     */
   publicstaticvoidmain(String[]args)throwsException {
       longstart= System.currentTimeMillis();
        DemoClientclient = newDemoClient("localhost", 50051);
       try{
           /* Access a service running on the local machine on port 50051 */
            Stringuser ="world";
           client.greet(user);
            System.out.println("耗時:"+ (System.currentTimeMillis() -start) +"ms");
        }finally{
           client.shutdown();
        }
        System.out.println(
                System.currentTimeMillis() +"耗時:"+ (System.currentTimeMillis() -start) +"ms");
    }
}