转:https://segmentfault.com/a/1190000017144329?utm_source=tag-newest
https://github.com/protocolbuffers/protobuf/releases
当前下载protobuf2的最后一个版本
wget https://github.com/google/protobuf/archive/v2.6.1.zip
unzip v2.6.1.zip -d ./
cd protobuf-2.6.1
请根据自己的需求下载对应的版本,当前操作演示版本为protobuf2,及.proto文件中 syntax = "proto2";开头的
sudo apt-get install autoconf automake libtool
其他非debian发行版的机器安装对应的依赖扩展即可
./autogen.sh
如果无法连接google网站
修改
curl http://googletest.googlecode.com/files/gtest-1.5.0.tar.bz2 | tar jx
mv gtest-1.5.0 gtest
为
wget https://github.com/google/googletest/archive/release-1.5.0.tar.gz
tar xzvf release-1.5.0.tar.gz
mv googletest-release-1.5.0 gtest
也可由手动删除google的连接,直接下载文件并解压
./configure -h
./configure prefix=/opt/protobuf2
make && make install
权限不够的话,要使用sudo
ln -s /opt/protobuf2/bin/protoc /usr/local/bin/protoc
建立软连接,就可以直接使用protoc命令了
protoc --proto_path=/home/zhangsan/protobuf --python_out=/home/zhangsan/python /home/zhangsan/protobuf/test.proto
参数proto_path指明.proto文件所在位置,如果不写,会提示以下内容:
/home/zhangsan/protobuf/test.proto: File does not reside within any path specified using --proto_path (or -I). You must specify a --proto_path which encompasses this file. Note that the proto_path must be an exact prefix of the .proto file names -- protoc is too dumb to figure out when two paths (e.g. absolute and relative) are equivalent (it's harder than you think).
所以务必写上.proto文件所在目录路径
python_out即.py生成的目录
最后一个参数即为.proto文件的绝对路径
这行代码如果使用IDE,提示无相关的类库的话,直接删掉/注释即可
from google.protobuf import symbol_database as _symbol_database
生成的.py文件中,一下内容可能报类缺少之类的问题,也可删掉、注释
_sym_db.RegisterMessage
文件中包含的空的数组 oneofs也可能给导致异常,删掉、注释即可
oneofs=[],
最后调整一下文件的代码风格即可使用
request = DemoRequest()
request.user.id = 1
request.user.name = 'zhangsan'
body = request.SerializeToString()
# body 既可以使用http发送
response = http_func_name(body)
message = response.getBody()
message.ParseFromString()
# message 即为对应的数据对象
print(message.blog.id)
print(message.blog.title)
https://github.com/allegro/php-protobuf/releases
wget https://github.com/allegro/php-protobuf/archive/v0.12.3.zip
unzip v0.12.3.zip -d ./
cd php-protobuf-0.12.3
phpize
./configure
make
make install
extension=protobuf.so
在扩展配置部分加入以上内容,执行 php -ir | grep protobuf输出protobuf扩展信息即为正常,如:
protobuf
PWD => /home/qingliu/soft/php-protobuf-0.12.3
$_SERVER['PWD'] => /home/qingliu/soft/php-protobuf-0.12.3
composer install 安装即可
protoc --proto_path=/home/zhangsan/protobuf --plugin=protoc-gen-allegrophp=protoc-gen-php.php --allegrophp_out=/home/zhangsan/php /home/zhangsan/protobuf/test.proto
请在allegro/php-protobuf的源码目录执行,正常执行完上述命令后,可以在 /home/zhangsan/php目录中看到生成的php文件,php无需修改,即可使用,如不符合自己的项目规范,可以自行调节
使用这个composer包就行啦
composer require ruoge3s/protobuf-message-helper