在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
refer: PHP读写protobuf3示例 二.安装protobuf编译器 cd protobuf ./autogen.sh make
三.安装php扩展 To use PHP runtime library requires:
syntax = "proto3"; package Playwhale; message Person{ string name = 1; int32 age = 2; string email = 3; enum PhoneType{ HOME = 0; MOBILE = 1; WORK = 2; } message Phone{ int64 id = 1; PhoneType type = 2; } repeated Phone phoneNum = 4; } message UserList{ string name = 1; repeated Person users = 2; } 3.测试 <?php /** * Created by PhpStorm. * User: meng * Date: 18-10-17 * Time: 下午3:26 */ $start_time = microtime(true); $start_mem = memory_get_usage(); include 'Autoloader.php'; use Playwhale\Person; $from = new \Playwhale\Person(); $from->setName('jack'); $from->setAge(100); $from->setEmail('foo bar, this is a message'); //phone $phones = array(); $phone_obj = new \Playwhale\Person\Phone(); $phone_obj->setId(10000); $phone_obj->setType(\Playwhale\Person\PhoneType::HOME); $phones[] = $phone_obj; $phone_obj = new \Playwhale\Person\Phone(); $phone_obj->setId(30000); $phone_obj->setType(\Playwhale\Person\PhoneType::WORK); $phones[] = $phone_obj; $from->setPhoneNum($phones); //$encode_data = $from->serializeToString(); $encode_data = $from->serializeToString(); printf("encode_data=%s\n", $encode_data); printf("from: phoneNum=%s\n", json_encode($from->getPhoneNum())); file_put_contents('data.bin', $encode_data); echo "\n"; echo "\n"; $to = new \Playwhale\Person(); $to->mergeFromString($encode_data); printf("name=%s\n", $to->getName()); printf("age=%s\n", $to->getAge()); printf("email=%s\n", $to->getEmail()); foreach ($to->getPhoneNum() as $tmp_phone_obj) { printf("phone: id=%s, type=%s\n", $tmp_phone_obj->getId(), $tmp_phone_obj->getType()); } echo "\n"; echo "\n"; $end_time = microtime(true); $end_mem = memory_get_usage(); $mem = ($end_mem - $start_mem) / 1024 / 1024; printf("\nlast seconds=%ss, lost_mem=%sm ok.\n", $end_time-$start_time, $mem); <?php class Autoloader { /** * Load files by namespace. * * @param string $name * @return boolean */ public static function loadByNamespace($name) { $class_path = str_replace('\\', DIRECTORY_SEPARATOR, $name); if (strpos($name, 'Google\\') === 0 || strpos($name, 'GPBMetadata\\') === 0) { $class_file = __DIR__ . '/../src/'. $class_path. '.php'; //如果通过php扩展使用protobuf,则这里的处理可以忽略. } elseif (strpos($name, 'Playwhale\\') === 0) { $class_file = __DIR__. '/pb/'. $class_path . '.php'; } if (!is_file($class_file)) { if(strpos($name, 'GPBMetadata\\') === 0) $class_file = __DIR__. '/pb/' . $class_path . '.php'; } if (is_file($class_file)) { include_once($class_file); if (class_exists($name, false)) { return true; } } return false; } } spl_autoload_register('Autoloader::loadByNamespace'); d.测试结果 2).使用php原生语言包测试: 3).使用php扩展有更好的性能表现,比另一个使用方法提高20到30倍.
五.总结
|
2022-08-17
2022-11-06
2022-08-15
2022-08-18
2022-08-16
请发表评论