2012-11-12 66 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是私有財產的運輸類,不應該被訪問。