protobuf 个人理解就是一种数据格式,只不过在序列化后的大小、序列化、反序列化方面更优秀一些。
demo 是用spring boot做了一个server,一个test。server暴露出来的服务是rest的,数据格式就是protobuf。
直接上代码
common:
proto数据结构文件
syntax = "proto3";
// package comp.protobuf.pb;
option java_package = "com.protobuf.model";
option java_outer_classname = "UserProto";
message User {
int64 id = 1;
string name = 2;
message PhoneNumber {
string number = 1;
}
repeated PhoneNumber phone = 4;
}
生成对应语言的类,我这直接用java 的runtime,也可以直接再cmd中操作
package com.protobuf;
import java.io.IOException;
public class GenerateClass {
public static void main(String[] args) {
String protoFile = "user.proto";//
String strCmd = "D:/software/protobuf-3.3.0/protoc.exe --java_out=./src/main/java ./src/main/resources/"+ protoFile;
try {
Runtime.getRuntime().exec(strCmd);
} catch (IOException e) {
e.printStackTrace();
}//通过执行cmd命令调用protoc.exe程序
}
}
生成的java类文件 UserProto.java
2. server port:8080
application, controller
package com.protobuf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.web.bind.annotation.PathVariable;
import