1,idea 下载插件Protobuf support
setting->Plugins 搜索;安装完成之后重启IDEA
2,建立好maven项目之后引入Protobuf 和 grpc
<properties> <grpc.version>1.17.1</grpc.version> <protobuf.version>3.5.0</protobuf.version> </properties>
<dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java-util</artifactId> <version>3.5.1</version> </dependency>
3,引入插件
<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.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <protocArtifact> com.google.protobuf:protoc:3.5.0:exe:${os.detected.classifier} </protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact> io.grpc:protoc-gen-grpc-java:1.17.1:exe:${os.detected.classifier} </pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins>
此处的Plugins 和 PluginManagement 处于同一级,不然在右边的Plugins里面看不见ProtoBuf 插件
4,创建proto文件
proto文件夹,名字不能乱写,*.proto放在文件夹里面
Student.proto 内部数据:
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; }
5,点击Protobuf插件的compile就可以在target中生成java文件了,拷贝到com目录下,就可以使用了;
6,测试一下
@Test public void protobufTest() { ProtoDemo.Student.Builder builder = ProtoDemo.Student.newBuilder(); builder.setEmail("280208673@qq.com"); builder.setName("zhou"); builder.setId(100); ProtoDemo.Student student = builder.build(); System.out.println(student); System.out.println("=============== to byte"); for (byte b : student.toByteArray()) { System.out.println(b); } byte[] bytes = student.toByteArray(); try { ProtoDemo.Student student1 = ProtoDemo.Student.parseFrom(bytes); System.out.println("email:" + student1.getEmail()); System.out.println("name:" + student1.getName()); System.out.println("id:" + student1.getId()); } catch (InvalidProtocolBufferException e) { } }
可以正常输出;