GRPC 配置、使用、安装文档 java-windows


官方文档: http://www.grpc.io/
目录:
一、利用maven compile 来将proto生成java文件
二、利用exe手动命令生成java文件
三、利用gradle build 来将proto生成java文件
四、编写service 和 client for java

一、利用maven compile 将proto生成java文件
1.编写 .proto 文件 。命名为 : grpc-helloworld.proto .文件内容如下:    (protobuf3 语法:https://developers.google.com/protocol-buffers/docs/proto3
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;
}

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 

    文档介绍:https://developers.google.com/protocol-buffers/docs/proto3

    下载地址:https://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.2/

    下载完成后,添加 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 io.grpc.examples.helloworld.HelloWorldServer;
import io.grpc.stub.StreamObserver;
/**
 * A simple client that requests a greeting from the {@link HelloWorldServer} .
 */
public class DemoClient {
    private final ManagedChannel channel ;
    private final GreeterGrpc.GreeterStub stub ;
    private int count = 1;
    /** Construct client connecting to HelloWorld server at {@code host:port}. */
    public DemoClient(String host, int port) {
        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 );

    }
    public void shutdown() throws InterruptedException {
        channel .shutdown().awaitTermination(5, TimeUnit. SECONDS );
    }
    /** Say hello to server. */
    public void greet(String name) {
        try {
            final CountDownLatch finishLatch = new CountDownLatch(1);
            StreamObserver<HelloRequest> ob = stub .sayHello( new StreamObserver<HelloReply>() {
                @Override
                public void onNext(HelloReply value) {
                    System. out .println( "response:" + value.getMessage() + count );
                    count ++;
                }
                public void onError(Throwable t) {
                    System. err .println( "client demo error:" + t.getMessage());
                    finishLatch.countDown();
                }
                public void onCompleted() {
                    System. out .println( "finished demo" );
                    finishLatch.countDown();
                }
            });
            Thread.sleep(400);
            HelloRequest reply = HelloRequest.newBuilder().setName(name).build();
            System. out .println(System.currentTimeMillis());
            for ( int i = 0; i < 1; i++) {
                ob.onNext(reply);
            }
            ob.onCompleted();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * Greet server. If provided, the first element of {@code args} is the name to use in the
     * greeting. 客户端如果5秒没收到响应,则断开连接。
     */
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        DemoClient client = new DemoClient( "localhost" , 50051);
        try {
            /* Access a service running on the local machine on port 50051 */
            String user = "world" ;
            client.greet(user);
            System. out .println( "耗时:" + (System.currentTimeMillis() - start) + "ms" );
        } finally {
            client.shutdown();
        }
        System. out .println(
                System.currentTimeMillis() + "耗时:" + (System.currentTimeMillis() - start) + "ms" );
    }
}







  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
grpc-server-spring-boot-starter是一个基于Spring Boot框架的gRPC服务器的启动器。gRPC(Google Remote Procedure Call)是一种高性能的远程过程调用框架,它使用Protocol Buffers作为接口定义语言,并支持多种编程语言。 grpc-server-spring-boot-starter提供了一系列简化配置和集成的功能,使得在Spring Boot应用中启动和配置gRPC服务器变得更加容易。它提供了自动装配的功能,可以根据应用的配置自动创建和启动gRPC服务器。用户只需要在配置文件中设置相应的参数,如服务器的端口号、TLS证书等,即可完成服务器的启动配置。 在使用grpc-server-spring-boot-starter时,用户可以方便地定义服务接口和实现类。通过使用gRPC的接口定义语言(protobuf)定义接口,并生成对应的Java代码。然后,用户只需要在实现类中实现相应的接口方法即可。 在服务器启动后,grpc-server-spring-boot-starter会根据定义的接口和实现类,自动创建相应的gRPC服务,并将其注册到服务器中。当客户端发起远程调用时,服务器会根据接口定义和方法参数,将请求转发给对应的实现类,并返回执行结果给客户端。 grpc-server-spring-boot-starter还支持对gRPC服务器进行拦截器的配置。拦截器可以在请求和响应的过程中拦截和修改消息,用于实现日志记录、鉴权、性能监控等功能。 总之,grpc-server-spring-boot-starter简化了在Spring Boot应用中使用gRPC配置和集成过程,使得开发者可以更加便捷地构建和部署gRPC服务器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值