前提
最近在手?jǐn)]IM相關(guān)的APP,想著后臺(tái)傳輸數(shù)據(jù)用
protobuf來(lái)會(huì)方便一些,奈何自己剛開(kāi)始接觸SpringBoot時(shí)間不長(zhǎng),有些東西不是很清楚,使用期間遇到了一些問(wèn)題。但是,最終還是解決了,今天寫(xiě)這篇文章主要是記錄以下Springboot中通過(guò)grpc的方式使用protobuf
注意:關(guān)于 protobuf的相關(guān)解釋不說(shuō)了,如果不清楚可以移步Android Protobuf 使用初探,查看相關(guān)內(nèi)容
首先
關(guān)于
Springboot中如何使用protobuf,請(qǐng)看下面的配置,網(wǎng)上其他文章說(shuō)可以添加protobuf的插件,各位可以根據(jù)自己的具體情況添加。
-
1、打開(kāi)
pom.xml文件,在properties節(jié)點(diǎn)下添加protobuf和grpc的版本<properties> <grpc.version>1.6.1</grpc.version> <protobuf.version>3.3.0</protobuf.version> <java.version>1.8</java.version> </properties> -
2、在
dependencies節(jié)點(diǎn)下添加protobuf和grpc的maven依賴<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> -
3、在
build節(jié)點(diǎn)下添加maven<extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.5.0.Final</version> </extension> </extensions> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins>
其次
這一步是創(chuàng)建
protobuf文件并且生成對(duì)應(yīng)的java文件
- 1、在
src/main下面創(chuàng)建proto包,并且在里面創(chuàng)建Msg.proto文件,如下圖所示

-
2、寫(xiě)入protobuf內(nèi)容
syntax = "proto3"; option java_outer_classname = "MessageProtoBuf";// 指定生成的類名 message Msg { Head head = 1;// 消息頭 string body = 2;// 消息體 } message Head { string msgId = 1;// 消息id int32 msgType = 2;// 消息類型 int32 msgContentType = 3;// 消息內(nèi)容類型 string fromId = 4;// 消息發(fā)送者id string toId = 5;// 消息接收者id int64 timestamp = 6;// 消息時(shí)間戳 int32 statusReport = 7;// 狀態(tài)報(bào)告 string extend = 8;// 擴(kuò)展字段,以key/value形式存放的json } -
3、開(kāi)始編譯,生成對(duì)應(yīng)的java文件,如下圖所以,依次點(diǎn)擊,就會(huì)在
target文件夾下生成對(duì)應(yīng)的java類
image.png -
4、如下圖所示,
target文件夾下就會(huì)生成對(duì)應(yīng)的java文件
image.png
注意:我這里指定的protobuf的文件名為MessageProtoBuf,當(dāng)然你也可以自定義。
最后
好了,這就是今天的
Springboot使用grpc的方式添加protobuf的文章,如果有疑問(wèn)可以進(jìn)水群(493180098)探討。

