【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
Google Protocol Buffer 专门用来串行化和反串行化对象,但官方仅实现了C++、Python、Java三种语言。其他语言版本也相继由不同的作者来实现。虽然有一定缺陷,也足以在大部分的项目中使用了。
.proto 的基本写法:
package feeds;
message Feed {
optional string title = 1;
message Entry {
optional string title = 1;
}
repeated Entry entry = 2;
}
Python、C++、Java三种语言版本请见
https://developers.google.com/protocol-buffers/docs/reference/overview
代码生成:
<?php
require_once('../parser/pb_parser.php');
$test = new PBParser();
$test->parse('./feeds.proto');
?>
串行化:
<?php
require_once('message/pb_message.php');
require_once('pb_proto_test.php');
$feed = new Feed();
$feed->set_title('asdf');
$t = $feed->add_entry();
$t->set_title('dddd');
$bin = $feed->SerializeToString();
?>
反串行化:
<?php
require_once('message/pb_message.php');
require_once('pb_proto_test.php');
$feed = new Feed();
$feed->ParseFromString($bin);
?>
Node.js版本:
https://npmjs.org/package/protobuf
代码生成:
protoc --descriptor_set_out=feeds.desc --include_imports feeds.proto
串行化与反串行化:
var fs = require('fs');
var Schema = require('protobuf_for_node').Schema;
var schema = new Schema(fs.readFileSync('feeds.desc'));
var Feed = schema['feeds.Feed'];
var aFeed = Feed.parse(aBuffer);
var serialized = Feed.serialize(aFeed);
来源:oschina
链接:https://my.oschina.net/u/107503/blog/146323