带有nodejs示例的Apache Thrift

时间:2012-11-12 13:44:00

标签: node.js serialization deserialization thrift

我正在尝试使用Apache Thrift在以不同语言实现的应用程序之间传递消息。它不一定用作RPC,而是用于序列化/反序列化消息。 一个应用程序在node.js.我试图找出Apache thrift如何与node.js一起工作,但我找不到太多的文档和示例,除了一个关于Cassandra的小文章和例子: https://github.com/apache/thrift/tree/trunk/lib/nodejs

同样,我不需要在.thrift文件中声明任何过程,我只需序列化一个简单的数据结构,如:

struct Notification {
   1: string subject,
   2: string message
 }

任何人都可以帮我一个例子吗?

3 个答案:

答案 0 :(得分:6)

我终于通过查看nodejs的库来浪费了大量时间,找到了这个问题的答案。

//SERIALIZATION:
var buffer = new Buffer(notification);
var transport = new thrift.TFramedTransport(buffer);
var binaryProt = new thrift.TBinaryProtocol(transport);
notification.write(binaryProt);

此时,可以在transport.outBuffers字段中找到字节数组:

var byteArray = transport.outBuffers;

反序列化:

var tTransport = new thrift.TFramedTransport(byteArray);
var tProtocol = new thrift.TBinaryProtocol(tTransport);
var receivedNotif = new notification_type.Notification();
receivedNotif.read(tProtocol);

还需要将以下行添加到nodejs库的index.js文件中以进行thrift:

exports.TFramedTransport = require('./transport').TFramedTransport;
exports.TBufferedTransport = require('./transport').TBufferedTransport;
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol;

此外,nodejs库中至少还有一个错误。

答案 1 :(得分:4)

上面的答案是错误的,因为它试图直接使用outBuffers,这是一个缓冲区数组。这是一个使用thrift和nodejs的工作示例:

var util = require('util');
var thrift = require('thrift');

var Notification = require('./gen-nodejs/notification_types.js').Notification;

var TFramedTransport = require('thrift/lib/thrift/transport').TFramedTransport;
var TBufferedTransport = require('thrift/lib/thrift/transport').TBufferedTransport;
var TBinaryProtocol = require('thrift/lib/thrift/protocol').TBinaryProtocol;

var transport = new TFramedTransport(null, function(byteArray) {
  // Flush puts a 4-byte header, which needs to be parsed/sliced.
  byteArray = byteArray.slice(4);

  // DESERIALIZATION:
  var tTransport = new TFramedTransport(byteArray);
  var tProtocol = new TBinaryProtocol(tTransport);
  var receivedNotification = new Notification();
  receivedUser.read(tProtocol);

  console.log(util.inspect(receivedNotification, false, null));
});

var binaryProt = new TBinaryProtocol(transport);

// SERIALIZATION:
var notification = new Notification({"subject":"AAAA"});
console.log(util.inspect(notification, false, null));
notification.write(binaryProt);
transport.flush();

答案 2 :(得分:1)

DigitalGhost是对的,前面的例子是错误的。 恕我直言,outBuffers是传输类的私有属性,不应被访问。