GRPC学习笔记(1)

看了GRPC的官方文档,说句大实话,没怎么看懂,都是一些新名词,如果只是想马上上手,其他的不用看,但是Protobuf一定要看.

推荐几个官网,学习必看,不然你可能都看不懂代码
写proto3必看https://developers.google.com/protocol-buffers/docs/proto3
gRPC官方文档https://grpc.io/docs/guides/
protocol-buffers官方文档https://developers.google.com/protocol-buffers/

然后的话讲一讲protobuf在IDEA中的基本使用.其他也是类似
首先在IDEA创建一个MAVEN项目
在这里插入图片描述怎么创建maven就不讲了这个不会直接百度,创建好以后,如图
在这里插入图片描述然后就可以安装一个protobuf,这个插件的作用应该是能让IDEA识别以.proto结尾的文件(具体的也不大清楚)我这里是已安装的,所以是灰色的,如果没安装应该是像右边那样绿色的,点击安装就好了,安装好以后记得重启IDEA就可以
在这里插入图片描述然后我附上我的porm文件的所有依赖,可以直接复制就可以

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.grpc</groupId>
    <artifactId>examples</artifactId>
    <packaging>jar</packaging>
    <!-- Feel free to delete the comment at the end of these lines. It is just
         for safely updating the version in our release process. -->
    <version>1.21.0</version><!-- CURRENT_GRPC_VERSION -->
    <name>examples</name>
    <url>https://github.com/grpc/grpc-java</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <grpc.version>1.21.0</grpc.version><!-- CURRENT_GRPC_VERSION -->
        <protobuf.version>3.7.1</protobuf.version>
        <protoc.version>3.7.1</protoc.version>
        <!-- required for jdk9 -->
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-bom</artifactId>
                <version>${grpc.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
            <scope>provided</scope> <!-- not needed at runtime -->
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-testing</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java-util</artifactId>
            <version>${protobuf.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.25.1</version>
            <scope>test</scope>
        </dependency>



    </dependencies>


    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.5.0.Final</version>
            </extension>
        </extensions>

        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.4.1</version>
                <executions>
                    <execution>
                        <id>enforce</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireUpperBoundDeps/>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
<!-- .proto生成.java文件所需要的依赖-->
            <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.11.0:exe:${os.detected.classifier}
                </pluginArtifact>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>

           </plugin>
        </plugins>
    </build>

</project>

配置完毕

现在开始写.proto文件,在src/main下面新建proto文件夹,文件夹的名字与上面的配置有关,采用的是默认的,所以名字不要乱改!
在这里插入图片描述在proto里面新建file,后缀.proto
在这里插入图片描述Student中代码为:

syntax = "proto3";
//生成文件所在包名
option java_package = "com.demo";
//生成的java文件名
option java_outer_classname = "ProtoDemo";

message Student {
    int32 id = 1;
    string name = 2;
    string email = 3;
    //枚举类
    enum Sex {
        MAN = 0;
        WOMAN = 1;
    }
    Sex sex = 4;

    enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
    }
    //内部类
    message PhoneNumber {
        string number = 1;
        PhoneType type = 2;
    }
    //集合
    repeated PhoneNumber phone = 5;
}

编写好.proto文件后,使用插件将proto文件转换为java文件
在这里插入图片描述双击protobuf:compile就可以直接生成.java文件,就会出现下图build success然后在target文件中就可以找到对应的.java文件
在这里插入图片描述在这里插入图片描述然后将ProtoDemo.java这个文件直接移动到上面,这里遇到一点坑,最好包结构可以和target里面的包结构可以一样,不然复制过去会报错,还有一个办法是在生成的时候将下图的包名和生成的文件名字改为你将来要将这个文件移动到那个地方的包名,这样就可以避免移动后报错。
在这里插入图片描述
移动到需要使用的文件夹后的截图
在这里插入图片描述然后在同包下写一个Test文件如上图,用来测试、之前生成的代码

package com.demo;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;

import java.util.List;

/**
 * @author jiangli
 * @date 2018/4/26 14:44
 * protobuf是一种数据交换的格式,以二进制的格式进行数据交换,主要用于网络传输、配置文件、数据存储等诸多领域
 */
public class Test {
    public static void main(String[] args) {
        //获取Student对象
        //这里的Student对象构造器被私有化,我们通过Student的内部类Builder来构建builder
        ProtoDemo.Student.Builder builder = ProtoDemo.Student.newBuilder();
        //通过Student的内部类builder提供了构建Student相关属性的set方法
        builder.setId(1);
        builder.setName("凌晨0点0分");
        builder.setEmail("31346337@qq.com");
        builder.setSex(ProtoDemo.Student.Sex.MAN);
        //获取PhoneNumber对象
        ProtoDemo.Student.PhoneNumber.Builder builder1 = ProtoDemo.Student.PhoneNumber.newBuilder();
        builder1.setNumber("13657177663");
        builder1.setType(ProtoDemo.Student.PhoneType.MOBILE);
        ProtoDemo.Student.PhoneNumber pn = builder1.build();
        builder.addPhone(pn);
        //再创建1个PhoneNumber对象
        pn = ProtoDemo.Student.PhoneNumber.newBuilder()
                .setNumber("13581491939").setType(ProtoDemo.Student.PhoneType.HOME).build();
        builder.addPhone(pn);
        //序列化
        ProtoDemo.Student stu = builder.build();
        System.out.println("protobuf数据大小: " + stu.toByteString().size());
        //再将封装有数据的对象实例,转换为字节数组,用于数据传输、存储等
        byte[] stuByte = stu.toByteArray();
        //这里得到了stuBte字节数组后,我们可以将该数据进行数据传输或存储,这里至于用什么技术传输就根据具体情况而定
        //假如这里stuByt通过传输,下面的代码接到了该数据
        //接收方 ,这里为了方便我们就写在一个类里面
        //将字节数据反序列化为对应的对象实例
        ProtoDemo.Student student = null;
        try {
            student = ProtoDemo.Student.parseFrom(stuByte);
            //这里得到了Student实例了,就可以根据需要来操作里面的数据了
            System.out.println("学生ID:" + student.getId());
            System.out.println("姓名:" + student.getName());
            System.out.println("性别:" + (student.getSex().getNumber() == 0 ? "男" : "女"));
            System.out.println("邮箱:" + student.getEmail());
            //遍历phoneNumber字段
            List<ProtoDemo.Student.PhoneNumber> phList = student.getPhoneList();
            for (ProtoDemo.Student.PhoneNumber p : phList) {
                System.out.println(p.getType() + "电话:" + p.getNumber());
            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        /*如何快速的进行json格式化*/
        String jsonObject = "";
        try {
            jsonObject = JsonFormat.printer().print(student);
        } catch (InvalidProtocolBufferException e) {
            e.getMessage();
        }
        System.out.println(jsonObject.toString());
        System.out.println("json数据大小: " + jsonObject.getBytes().length);
    }
}

运行Test文件后控制台输出
在这里插入图片描述Demo效果基本完成,可以看到能将protobuf对象序列化成二进制数组,也能将二进制数组反序列化成protobuf对象.

更牛逼的是还能将protobuf对象转换成json!转换成json方便给前端使用.通过比较可以看出protobuf的大小只有json的1/3.

当然protobuf还有其他更多的优势.

本文参照下述文章做修改,如要查看文章请点击一下链接
参考文章:https://blog.csdn.net/qq_39940205/article/details/80095302

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值