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

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

2.新建maven專案,將.proto放入src/main/proto資料夾下面 3、編寫pom.xml檔案,引入外掛
<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.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目錄下 重新整理專案即可 二、利用exe手動命令生成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 apply plugin: 'java' apply plugin: '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. def grpcVersion = '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. apply plugin: '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. apply plugin: 'application' startScripts.enabled = false task routeGuideServer(type: CreateStartScripts) {   mainClassName = 'io.grpc.examples.routeguide.RouteGuideServer'   applicationName = 'route-guide-server'   outputDir = new File(project.buildDir, 'tmp')   classpath = jar.outputs.files + project.configurations.runtime } task routeGuideClient(type: CreateStartScripts) {   mainClassName = 'io.grpc.examples.routeguide.RouteGuideClient'   applicationName = 'route-guide-client'   outputDir = new File(project.buildDir, 'tmp')   classpath = jar.outputs.files + project.configurations.runtime } task helloWorldServer(type: CreateStartScripts) {   mainClassName = 'io.grpc.examples.helloworld.HelloWorldServer'   applicationName = 'hello-world-server'   outputDir = new File(project.buildDir, 'tmp')   classpath = jar.outputs.files + project.configurations.runtime } task helloWorldClient(type: CreateStartScripts) {   mainClassName = 'io.grpc.examples.helloworld.HelloWorldClient'   applicationName = 'hello-world-client'   outputDir = new File(project.buildDir, 'tmp')   classpath = jar.outputs.files + project.configurations.runtime } task compressingHelloWorldClient(type: CreateStartScripts) {   mainClassName = 'io.grpc.examples.experimental.CompressingHelloWorldClient'   applicationName = 'compressing-hello-world-client'   outputDir = new File(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()方法來操作服務端的開始停止,完整程式碼如下: package com.ibm.crl.demo; import java.io.IOException; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; public class DemoServer { private Server server; /* The port on which the server should run */ private int port = 50051; private void start() throws IOException { server = ServerBuilder.forPort(port).addService(new DemoGrpcImpl()).build().start();         System.out.println("server start " + port);         Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // 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");             }         });     } private void stop() { if (server != null) { server.shutdown();         }     } /**      * Await termination on the main thread since the grpc library uses daemon threads.      */ private void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination();         }     } /**      * Main launches the server from the command line.      */ public static void main(String[] args) throws IOException, InterruptedException { final DemoServer server = new DemoServer(); server.start(); server.blockUntilShutdown();     } static class DemoGrpcImpl extends GreeterGrpc.GreeterImplBase { @Override public StreamObserver<HelloRequest> sayHello(StreamObserver<HelloReply> responseObserver) { return new StreamObserver<HelloRequest>() { private int count = 0; public void onNext(HelloRequest req) { try {                         Thread.sleep(2000);                     } catch (InterruptedException e) { e.printStackTrace();                     } count++;                     HelloReply reply =                             HelloReply.newBuilder().setMessage("demo " + req.getName()).build(); responseObserver.onNext(reply);                     System.out.println("resquest:" + req.getName() + System.currentTimeMillis());                 } public void onError(Throwable t) {                     System.err.println(System.currentTimeMillis() + " : " + count                             + "server demo error:" + t.getMessage()); responseObserver.onError(t);                 } public void onCompleted() {                     System.out.println("task finish close session ! someone has died!"                             + System.currentTimeMillis() + " times:" + count); responseObserver.onCompleted();                 }             };         }     } } // end 2、編寫client,流 主要是初始化channel和GreeterStub程式碼如下: package com.ibm.crl.demo; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import

相關推薦

GRPC 配置使用安裝 java-windows

2.新建maven專案,將.proto放入src/main/proto資料夾下面 3、編寫pom.xml檔案,引入外掛 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSc

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/XMLSch

Java項目生成可執行jar包exe以及在Windows下的安裝

項目 pos 安裝jdk 通過 文件 options csdn 成了 應該 1、如何通過eclipse將Java項目生成可執行jar包 首先把在eclipse下的java項目導出jar file 下一步 下一步 下一步 最後點擊完成,便生成了可執行的jar文

Redis命令行和配置redis.windows.conf

存在 默認 localhost 字符串 con all get bsp 多行 一、Redis發送命令的兩種方式 redis-cli -h localhost -p 6379redis-cli ping 返回pong 證明正常 二、命令返回值 1、狀態回復,如ping命令

Head first java chapter 17 包jar存檔和部署

image bsp head .com ava 分享 logs cnblogs http Head first java chapter 17 包、jar存檔文件和部署

將cs快速的轉換成可執行和響應(配置編譯開關的)

文本文件 font OS reference 方便 sha 文本文 libraries rgs 1、將包含多個類型的源代碼文件轉換為可以部署的文件。有如下Program.cs的文件,代碼如下: public sealed class Program {

SpringBoot系列四:SpringBoot開發(改變環境屬性讀取資源Bean 配置模版渲染profile 配置

pat row 開發 ima set his 改變 端口配置 import 1、概念 SpringBoot 開發深入 2、具體內容 在之前已經基本上了解了整個 SpringBoot 運行機制,但是也需要清楚的認識到以下的問題,在實際的項目開發之中,尤其是 Java

Java 007 面向物件(構造方法static關鍵字JDK幫助Math類)

知識點梳理 心得體會 小知識點 1.不同型別的靜態變數 1>靜態變數是基本資料型別時,類的外部不用建立該類例項可以能直接使用 2>靜態變數是引用時,即靜態變數是一個物件的引用,必須先初始化這個物件,才能將引用指向靜態變數 2.靜態成員與例項成員 1&

Java 合併拆分PDF

處理PDF文件時,我們可以通過合併的方式,來任意組幾個不同的PDF檔案或者通過拆分將一個檔案分解成多個子檔案,這樣的好處是對文件的儲存、管理很方便。下面將通過Java程式程式碼介紹具體的PDF合併、拆分的方法。 工具 Free Spire.PDF for Java 2.0.0 (免費版) 注:

CDH完全安裝(含Spark2

本文主要記敘瞭如何在centos7.2上搭建cdh平臺,使用mysql為元資料管理庫(官方推薦),安裝了Spark2和Kafka元件。 一、軟體準備 cdh5.13.3-centos7.tar.gz cm5.13.3-centos7.tar.gz SPARK

AKKA(java版)—角色的引用路徑和地址

2.5 角色的引用、路徑和地址 這一章描述,角色在一個有可能是分散式的角色系統中是如何被識別和定位的。它關係到了角色系統形成的內在監管層級以及角色跨越多個網路節點之間通訊的位置透明化。 上述圖片顯示了角色系統中幾個最重要實體之間的關係,請仔細閱讀。 2.5.1什麼是一個角色引用? 一個角

GoogleIBM和Lyft開源的微服務管理框架Istio安裝

(題圖:威海東部海灣 May 28,2017) 前言 本文根據官網的文件整理而成,步驟包括安裝istio 0.1.5並建立一個bookinfo的微服務來測試istio的功能。 文中使用的yaml檔案可以在kubernetes-handbook的

Lesson_for_java_day23--java的網路程式設計練習(登入介面上傳上傳圖片通過網路文字轉換)

練習一、模擬賬戶登入介面 服務端: package Exercise; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.i

Java 加密解密PDF

本篇文章將介紹通過Java程式設計來設定PDF文件保護的方法。我們可以設定僅用於查閱文件的密碼,即該通過該密碼開啟文件時僅用於文件閱讀,無法編輯;也可以設定文件編輯許可權的密碼,即通過該密碼開啟文件時,文件為可編輯狀態。使用工具:Free Spire.PDF for Java V2.0.0(免費版)關於jar

Linux中怎麼檢視命令的幫助怎麼檢視系統配置檔案的幫助

引言:上期回顧(想要學習的童鞋可以點選看看) 上一章講訴了怎麼快速查詢檔案,以及怎麼找到一個命令所在位置,那麼這一章就來講怎麼檢視命令的幫助文件。在Linux命令中,我們是不會每個命令都會講到的,如果遇到沒有見過的命令該怎麼辦呢?建議大家先不要去問前輩,這樣自己的印象不會深

Java中抽象類介面包的練習

。一、選擇題 1.        實現介面的類修飾不可以是(   ) A.  Public    B、abstract     C、final     D、void 2.        下面程式定義了一個類,關於該類說法正確的是( ) abstract classabst

apache poi操作office----java線上預覽txtwordpptexecel,pdf程式碼

在頁面上顯示各種文件中的內容。在servlet中的邏輯 word:  BufferedInputStream bis = null;   URL url = null;   HttpURLConnection httpUrl = null; // 建立連結   u

Java 新增讀取刪除PPT屬性

文件屬性是一些描述性的資訊,它未包含在檔案的實際內容中,但提供了有關檔案的資訊,可用來幫助查詢和整理檔案。以下示例中將介紹通過Java程式來新增PPT文件屬性、讀取、刪除PPT文件中已有屬性的方法。   使用工具:Free Spire.Presentation for Java(免費版) Ja

Java 新增讀取刪除Excel屬性

在文件屬性中,可以設定諸多關於文件的資訊,如建立時間、作者、單位、類別、關鍵詞、備註等摘要資訊以及一些自定義的文件屬性。下面將通過Java程式來演示如何設定,同時對文件內的已有資訊,也可以實現讀取和刪除等操作。 示例大綱: 1. 新增文件屬性   1.1 新增摘要資訊   1.2 新增自定

關於Ubuntu中passwdshadowgroup等

之間 文件的 最重要的 關聯 ice use 並不是 字段 新用戶 轉自https://yq.aliyun.com/articles/50327 在Ubuntu系統中,/etc目錄下,有三個文件:passwd shadow group,可能我們已經在用了,但是沒有註意到其詳