当前位置: 首页 > Linux

linux下安装protobuf及其使用

时间:2023-04-06 04:01:21 Linux

linux下安装protobuf并在python和php上应用下载并解压源文件github上发布地址https://github.com/protocolbuffers/protobuf/releases下载&解压&进入源码目录当前下载最新版本的protobuf2wgethttps://github.com/google/protobuf/archive/v2.6.1.zipunzipv2.6.1.zip-d./cdprotobuf-2.6.1请根据需要下载对应版本,目前demo版本为protobuf2,.proto文件中的syntax="proto2";一开始的安装依赖sudoapt-getinstallautoconfautomakelibtool其他非debian发行版机器安装对应的依赖扩展生成configure文件。/autogen.sh如果无法连接google修改curlhttp://googletest.googlecode.com/files/gtest-1.5.0.tar.bz2|tarjxmvgtest-1.5.0gtest到wgethttps://github.com/google/googletest/archive/release-1.5.0.tar.gztarxzvfrelease-1.5.0.tar.gzmvgoogletest-release-1.5.0gtest也可以手动删除google连接,直接下载文件解压configure查看帮助。/configure-h指定安装目录。/configureprefix=/opt/protobuf2installmake&&makeinstall如果是权限不够,使用sudo建立软连接命令ln-s/opt/protobuf2/bin/protoc/usr/local/bin/protoc建立软连接,可以直接使用protoc命令。Python中的应用使用protobuf命令生成.py文件protoc--proto_path=/home/zhangsan/protobuf--python_out=/home/zhangsan/python/home/zhangsan/protobuf/test.proto参数说明参数proto_path表示.proto文件所在位置。如果没有写入,会提示如下内容:/home/zhangsan/protobuf/test.proto:Filedoesnotresideanypathspecifiedusing--proto_path(or-I).您必须指定包含此文件的--proto_path。请注意,proto_path必须是.proto文件名的精确前缀——protoc太笨了,无法弄清楚两个路径(例如绝对路径和相对路径)何时相等(这比你想象的要难)。所以一定要写上.proto文件所在的目录路径python_out,也就是.py生成的目录。最后一个参数是生成.proto文件的绝对路径文件优化修改这行代码如果使用IDE,如果提示没有相关类库,直接删除/注释即可。从google.protobufimportsymbol_databaseas_symbol_database生成的.py文件,下面的内容可能会报类丢失之类的问题,也可以删除注释掉_sym_db.RegisterMessage文件中包含的空数组oneofs,可能也会导致异常,删除注释oneofs=[]即可,最后调整文件代码风格使用应用(假设是根据用户信息获取用户博文)request=DemoRequest()request.user。id=1request.user.name='zhangsan'body=request.SerializeToString()#body可以使用http发送response=http_func_name(body)message=response.getBody()我ssage.ParseFromString()#message对应的数据对象print(message.blog.id)print(message.blog.title)应用在PHP下载allegro/php-protobufgithub版本发布页面https://github.com/allegro/php-protobuf/releases下载最新版本(2018.11.26版本为v0.12.3)wgethttps://github.com/allegro/php-protobuf/archive/v0.12.3.zip解压到当前目录unzipv0.12.3.zip-d./installphpextensioncdphp-protobuf-0.12.3phpize./configuremakemakeinstallconfigurephp.iniextension=protobuf.so在扩展配置部分添加以上内容,执行php-ir|grepprotobuf输出protobufextension信息正常,如:protobufPWD=>/home/qingliu/soft/php-protobuf-0.12.3$_SERVER['PWD']=>/home/qingliu/soft/php-protobuf-0.12.3在源码目录安装allegro/php-protobuf依赖的php类库composerinstall安装并使用protobuf生成.php文件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无需修改即可使用。如果不符合你自己的项目规范,你可以调整IDEHelper来使用这个composer包。作曲家要求ruoge3s/protobuf-消息助手