前言
上一週由於一個需求,需要使用protobuf協議進行交互,但是網上關於php使用protobuf協議與服務端交互的資料十分少,以及難找,因此記錄一下。
ProtoBuf (Google Protocol Buffer)是由google公司設計的、用於數據交換的序列結構化數據格式,具有跨平臺、跨語言、可擴展等特性,類似於常用的XML及JSON,但它具有更小的傳輸體積、更高的編碼、解碼能力,特別適合於數據存儲、網絡數據傳輸等對存儲體積、實時性要求高的領域。
目前官方ProtoBuf 最新版本ProtoBuf3,已經支持多種語言:C++\C#\Go\Java\Python\Ruby\Object C \Javascript\PHP,並且提供工具很方便地根據不同語言產生ProtoBuf需要的類庫。
一、環境準備
centos7 64位
PHP7.0.1
二、安裝protobuf編譯器
1)安裝
本文使用的protobuf編譯器版本爲3.5.1。
官方發佈地址: https://github.com/google/protobuf/releases/tag/v3.5.1 。
把壓縮文件下載以後,進行解壓並安裝:
cd
mkdir downloads
cd downloads
sudo apt-get install autoconf automake libtool curl make g++ unzip
wget https://github.com/google/protobuf/releases/tag/v3.5.1
tar -zxvf protobuf-php-3.5.1.tar.gz
cd protobuf-3.5.1
./autogen.sh
./configure make make install
sudo ldconfig #refresh shared library cache.
2)校驗
執行以上命令之後,執行下面的命令 查看是否安裝成功,如果沒報錯,會顯示protobuf的版本
protoc --version
三、安裝php擴展
因爲這次需要在PHP下使用protobuf,所以還需要安裝protobuf在PHP下的擴展。
cd
cd downloads/protobuf-3.5.1/php/ext/google/protobuf
whereis phpize #找到phpize的具體路徑,根據個人按照php時的路徑不同而不同
/usr/local/php/bin/phpize
./configure && make && sudo make install
安裝完以後,找到php.ini的目錄,添加 protobuf 擴展。注意,需要根據個人的php安裝時指定的php.ini的放置目錄,不要照搬。
在php.ini中添加:
extension=protobuf.so
然後重啓php:
/etc/init.d/php-fpm restart
輸入以下命令校驗是否安裝並且配置成功:
php -m |grep protobuf
四、使用protobuf
1)首先爲了讓本次測試過程中,文件目錄結構清晰一點,我們創建一個測試文件夾 test 和 編譯後的類庫文件夾 pb
cd
mkdir test
mkdir pb
2)進入 test 文件夾,創建一個簡單的 proto 協議文件。使用 vim 編輯器創建並編輯hello.proto文件,並輸入如下字符:
syntax = "proto3";
package test;
message helloworld
{
int32 id = 1; // ID
string str = 2; // str
int32 opt = 3; // optional field
}
3)編譯協議文件:
protoc --proto_path=/root/test --php_out=/root/pb /root/test/hello.proto
4)這時會在 /root/pb 下,生成一個GPBMetadata的文件夾和Test的文件夾,如上圖所示。
5)然後在 /pb 目錄下,使用composer命令引入php的protobuf依賴類庫:
composer require google/protobuf
採用composer方式引入google/protobuf之後,項目中會出現一個vendor目錄。
6)繼續在 /pb 目錄下創建測試文件 testproto.php 。
<?php
include 'vendor/autoload.php';
include 'Test/helloworld.php';
include 'GPBMetadata/Hello.php'; #務必引入該文件,否則報錯
$from = new \Test\helloworld();
$from->setId(9527);
$from->setStr('Hello world, this is my message');
$from->setOpt(27);
//生成protobuf二進制數據
$data = $from->serializeToString();
$to = new \Test\helloworld();
//解析數據
$to->mergeFromString($data);
echo $to->getId() . PHP_EOL;
echo $to->getStr() . PHP_EOL;
echo $to->getOpt() . PHP_EOL;
7)最後我們我們執行 testproto.php 腳本,可以看到可以正常解析出protobuf結構的數據。
參考鏈接:
https://www.jianshu.com/p/ce098058edf0
https://blog.csdn.net/supergao222/article/details/78566716?locationNum=3&fps=1
https://www.jianshu.com/p/ace5d1e83266
https://blog.csdn.net/xy2204/article/details/84883018
https://blog.csdn.net/panjiapengfly/article/details/82456642
https://www.cnblogs.com/ginkgo-leaf/p/9805854.html
https://www.jianshu.com/p/8f764bfd90da