2012-11-12 68 views
5

我试图使用Apache节俭不同语言实现的应用程序之间传递消息。它不一定用作RPC,但更多用于序列化/反序列化消息。 一个应用程序在node.js中。我想弄清楚的Apache节俭如何与node.js的,但我找不到太多的文档和示例,除了在关于Cassandra的一个很小的一个: https://github.com/apache/thrift/tree/trunk/lib/nodejs阿帕奇节俭与例如的NodeJS

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

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

谁能帮我用一个例子?

回答

4

以上回答是错误的,因为它试图直接使用outBuffers,这是缓冲器阵列。下面是使用与节俭的的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(); 
+0

对不起,但您在同一个脚本中反序列化了已创建的相同数据。但是如果使用一些中间存储器(rabbitmq)在兔子里存储什么数据?切出缓冲区?或者每次调用flush并在回调中保存数据?并且对于byteArray使用片并不是每次都是好主意,因为它不复制数据,而是参考它。 – Selvatico

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文件节俭:

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

另外还有在图书馆的NodeJS至少一个错误。

1

DigitalGhost是正确的,前面的例子是错误的。 恕我直言outBuffers是私有财产的运输类,不应该被访问。