带有nodejs示例的Apache Thrift

Cla*_*ara 5 serialization thrift node.js deserialization

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

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

struct Notification {
   1: string subject,
   2: string message
 }
Run Code Online (Sandbox Code Playgroud)

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

Cla*_*ara 6

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

//SERIALIZATION:
var buffer = new Buffer(notification);
var transport = new thrift.TFramedTransport(buffer);
var binaryProt = new thrift.TBinaryProtocol(transport);
notification.write(binaryProt);
Run Code Online (Sandbox Code Playgroud)

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

var byteArray = transport.outBuffers;
Run Code Online (Sandbox Code Playgroud)

对于反序列化:

var tTransport = new thrift.TFramedTransport(byteArray);
var tProtocol = new thrift.TBinaryProtocol(tTransport);
var receivedNotif = new notification_type.Notification();
receivedNotif.read(tProtocol);
Run Code Online (Sandbox Code Playgroud)

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

exports.TFramedTransport = require('./transport').TFramedTransport;
exports.TBufferedTransport = require('./transport').TBufferedTransport;
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol;
Run Code Online (Sandbox Code Playgroud)

另外,nodejs库中至少还有一个错误.


Dig*_*ost 4

上面的答案是错误的,因为它尝试直接使用outBuffers,它是一个缓冲区数组。这是一个将 thrift 与 Node.js 结合使用的工作示例:

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();
Run Code Online (Sandbox Code Playgroud)