gRPC--JAVA(编译.proto)


1:创建.proto

syntax = "proto3"; //指定一个版本,这个必须是除了注释以外,位于文件的第一行

package com.example.demo;
//声明一个服务
service Greeter {

  rpc sayHello (HelloRequest) returns (HelloReply) {}

}
//定义一个请求消息
message HelloRequest {

  string name = 1;

}
//定义一个相应消息
message HelloReply {

  string message = 1;

}

2:添加配置信息

添加grpc包

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-all</artifactId>
    <version>1.10.1</version>
</dependency>

添加.proto文件编译工具

<build>
        <!--这个是为了下载下面的工具用的,他可以提供一些变量,os.detected.classifier变量可以根据当前系统的类型来下载对应的工具-->
        <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>
                <!--添加.proto文件的编译工具-->
                <configuration>
                    <!--protoc工具通过.proto文件生成对应的java对应的类-->
                    <protocArtifact>com.google.protobuf:protoc:3.0.0-beta-4:exe:${os.detected.classifier}</protocArtifact>
                    <!--protoc-gen-grpc-java工具通过.proto文件生成grpc工具类-->
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.15.0:exe:${os.detected.classifier}</pluginArtifact>
                    <!--这是生成grpc工具类存放的文件夹的名字-->
                    <pluginId>grpc</pluginId>
                    <!--要编译的.proto文件的路径-->
                    <protoSourceRoot>src/main/resources/proto</protoSourceRoot>
                </configuration>
                <executions>
                    <!--这是上面两个编译工具用到的命令-->
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>

用maven编译一下

 生成了两个文件:

java文件夹是protoc编译工具生成的代码

grpc文件夹是protoc-gen-grpc-java编译工具生成的工具类

GreeterGrpc是grpc的工具类

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM