Apache节点与nodejs示例

我正在尝试使用Apache Thrift在用不同语言实现的应用程序之间传递消息。 它不一定用作RPC,而更多用于序列化/反序列化消息。 一个应用程序在node.js中 我试图弄清楚Apache节点如何与node.js一起工作,但是我找不到太多的文档和例子,除了一个关于Cassandra的小问题: https : //github.com/apache/thrift/tree/躯干/ LIB /的NodeJS

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

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

谁能帮我一个例子?

上面的答案是错误的,因为它试图直接使用outBuffers,这是一个缓冲区数组。 以下是使用节点jj的节俭示例:

 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(); 

我终于find了这个问题的答案,浪费了很多时间,只是看着nodejs的库。

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

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

 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库中至less还有一个bug。

DigitalGhost是对的,前面的例子是错误的。 恕我直言,outbuffers是交通运输类的私人财产,不应该被访问。