## 13) 數據傳輸協議protocol buffer
### 13.1 簡介
**Google Protocol Buffer** (簡稱 Protobuf)是google旗下的一款輕便高效的結構化數據存儲格式,平臺無關、語言無關、可擴展,可用于通訊協議和數據存儲等領域。所以很適合用做數據存儲和作為不同應用,不同語言之間相互通信的數據交換格式,只要實現相同的協議格式即同一 proto文件被編譯成不同的語言版本,加入到各自的工程中去。這樣不同語言就可以解析其他語言通過 protobuf序列化的數據。目前官網提供了 C++,Python,JAVA,GO等語言的支持。google在2008年7月7號將其作為開源項目對外公布。
**tips:**
1. 啥叫平臺無關?Linux、mac和Windows都可以用,32位系統,64位系統通吃
2. 啥叫語言無關?C++、Java、Python、Golang語言編寫的程序都可以用,而且可以相互通信
3. 那啥叫可擴展呢?就是這個數據格式可以方便的增刪一部分字段啦~
4. 最后,啥叫序列化啊?解釋得通俗點兒就是把復雜的結構體數據按照一定的規則編碼成一個字節切片
### 13.2 數據交換格式
#### A)常用的數據交換格式有三種:
1. `json`: 一般的web項目中,最流行的主要還是 json。因為瀏覽器對于json 數據支持非常好,有很多內建的函數支持。
2. `xml`: 在 webservice 中應用最為廣泛,但是相比于 json,它的數據更加冗余,因為需要成對的閉合標簽。json 使用了鍵值對的方式,不僅壓縮了一定的數據空間,同時也具有可讀性。
3. `protobuf`: 是后起之秀,是谷歌開源的一種數據格式,適合高性能,對響應速度有要求的數據傳輸場景。因為 profobuf 是二進制數據格式,需要編碼和解碼。數據本身不具有可讀性。因此只能反序列化之后得到真正可讀的數據。
#### B)protobuf的優勢與劣勢
> 優勢:
1:序列化后體積相比Json和XML很小,適合網絡傳輸
2:支持跨平臺多語言
3:消息格式升級和兼容性還不錯
4:序列化反序列化速度很快,快于Json的處理速速
> 劣勢:
1:應用不夠廣(相比xml和json)
2:二進制格式導致可讀性差
3:缺乏自描述
------
### 13.3 protobuf環境安裝
##### A) protobuf 編譯工具安裝
1、下載 protoBuf:
```
cd $GOPATH/src/
git clone https://github.com/protocolbuffers/protobuf.git
```
2、或者直接將壓縮包拖入后解壓
```
unzip protobuf.zip
```
3、安裝依賴庫
```
sudo apt-get install autoconf automake libtool curl make g++ unzip libffi-dev -y
```
4、進入目錄
```
cd protobuf/
```
5、自動生成configure配置文件:
```
./autogen.sh
```
6、配置環境:
```
./configure
```
7、編譯源代碼(時間比較長):
```
make
```
8、安裝
```
sudo make install
```
9、刷新共享庫 (很重要的一步啊)
```
sudo ldconfig
```
10、成功后需要使用命令測試
```
protoc -h
```
#####
### 13.4 protobuf與C++編程
? 首先創建一個msg.proto文件,里面定義協議的格式
> protobuf_test/msg.proto
```protobuf
syntax="proto3";
package protobuf_test;
message helloworld
{
int32 id = 1; // ID
string str = 2; // str
int32 opt = 3; //optional field
}
```
? 寫好 proto 文件之后就可以用 Protobuf 編譯器將該文件編譯成目標語言了。本例中我們將使用 C++。
? 使用如下命令可以生成我們所需要的.cc與.h
```bash
protoc --cpp_out=. ./*.proto
```
? 執行上述命令將生成msg.pb.cc與msg.pb.h,執行時需要在文件msg.proto所在的目錄下執行。
為了方便,我們可以寫一個腳本,方便下次執行。
> build.sh
```bash
#!/bin/bash
protoc --cpp_out=. ./*.proto
```
> protobuf_test/write.cpp
```c
#include "msg.pb.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(void)
{
protobuf_test::helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output)) {
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
```
? Msg1 是一個 helloworld 類的對象,set_id() 用來設置 id 的.SerializeToOstream 將對象序列化后寫入一個 fstream 流。當擔序列化的接口還有很多比如SerializeToString, SerializeToArray等。
> protobuf_test/read.cpp
```c
#include "msg.pb.h"
#include <fstream>
#include <iostream>
using namespace std;
void ListMsg(const protobuf_test::helloworld & msg) {
cout << msg.id() << endl;
cout << msg.str() << endl;
}
int main(int argc, char* argv[]) {
protobuf_test::helloworld msg1;
fstream input("./log", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
ListMsg(msg1);
}
```
? 現在進行編譯:
```bash
$ g++ msg.pb.cc write.cpp -o write -lprotobuf
$ g++ msg.pb.cc read.cpp -o read -lprotobuf
```
? 執行,先執行write,再執行read。 write會將數據寫進log文件中,read可以通過pb協議解析出數據到內存變量中.
---
### 關于作者:
作者:`Aceld(劉丹冰)`
mail: [danbing.at@gmail.com](mailto:danbing.at@gmail.com)
github: [https://github.com/aceld](https://github.com/aceld)
原創書籍: [http://www.hmoore.net/@aceld](http://www.hmoore.net/@aceld)

>**原創聲明:未經作者允許請勿轉載, 如果轉載請注明出處**
- 一、Lars系統概述
- 第1章-概述
- 第2章-項目目錄構建
- 二、Reactor模型服務器框架
- 第1章-項目結構與V0.1雛形
- 第2章-內存管理與Buffer封裝
- 第3章-事件觸發EventLoop
- 第4章-鏈接與消息封裝
- 第5章-Client客戶端模型
- 第6章-連接管理及限制
- 第7章-消息業務路由分發機制
- 第8章-鏈接創建/銷毀Hook機制
- 第9章-消息任務隊列與線程池
- 第10章-配置文件讀寫功能
- 第11章-udp服務與客戶端
- 第12章-數據傳輸協議protocol buffer
- 第13章-QPS性能測試
- 第14章-異步消息任務機制
- 第15章-鏈接屬性設置功能
- 三、Lars系統之DNSService
- 第1章-Lars-dns簡介
- 第2章-數據庫創建
- 第3章-項目目錄結構及環境構建
- 第4章-Route結構的定義
- 第5章-獲取Route信息
- 第6章-Route訂閱模式
- 第7章-Backend Thread實時監控
- 四、Lars系統之Report Service
- 第1章-項目概述-數據表及proto3協議定義
- 第2章-獲取report上報數據
- 第3章-存儲線程池及消息隊列
- 五、Lars系統之LoadBalance Agent
- 第1章-項目概述及構建
- 第2章-主模塊業務結構搭建
- 第3章-Report與Dns Client設計與實現
- 第4章-負載均衡模塊基礎設計
- 第5章-負載均衡獲取Host主機信息API
- 第6章-負載均衡上報Host主機信息API
- 第7章-過期窗口清理與過載超時(V0.5)
- 第8章-定期拉取最新路由信息(V0.6)
- 第9章-負載均衡獲取Route信息API(0.7)
- 第10章-API初始化接口(V0.8)
- 第11章-Lars Agent性能測試工具
- 第12章- Lars啟動工具腳本