2011-05-24 38 views
2

我正在設計一個應用程序,它具有多個組件,主要用java和python編寫。 我正在考慮使用「JMS-Active MQ」作爲面向消息的中間件的組件和「協議緩衝區」。協議緩衝區作爲消息過活動Mq

1)這是繼續前進的好方法嗎?在我們的例子中,「消息大小」可以超過10MB,協議緩衝區對於跨組件通信仍然有優勢嗎?對於可以處理「海量數據」的跨平臺應用程序,是否有更好的通信「協議」?

2)我創建了一個概念證明,我通過「ActiveMQ」發送一個「協議愛好者」消息作爲消息,我在谷歌的java教程中使用樣例原型文件。

AddressBook.Builder book = AddressBook.newBuilder(); 
Person.Builder person = Person.newBuilder(); 
person.setName("mayank"); 
person.setId(2); 
book.addPerson(person); 
TextMessage message = session.createTextMessage(); 
message.setText(book.build().toString()); 

在另一個Java應用程序,我聽這個消息,並嘗試將其反序列化回通訊簿對象:

public void onMessage(Message message) { 
    TextMessage msg = (TextMessage) message; 
    try { 
     System.out.println(msg.getText()); 
     CodedInputStream stream =CodedInputStream.newInstance(msg.getText().getBytes()); 
     AddressBook book = AddressBook.parseFrom(stream); 
    } 
    catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

這造成了一個例外:

com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol 
    message, the input ended unexpectedly in the middle of a field. This could 
    mean either than the input has been truncated or that an embedded message 
    misreported its own length. 
at com.google.protobuf.InvalidProtocolBufferException.truncatedMessage(InvalidProtocolBufferException.java:49) 

我不知道怎麼了 ..?

回答

1

主要問題是由於某些原因,您正在使用TextMessage而不是正確選擇BytesMessage:protobuf是二進制編碼,而不是文本。 如果你絕對想濫用TextMessage作爲非文本消息,你必須指定編碼用於getBytes();並且使用編碼必須匹配任何用於將二進制有效載荷轉換爲字節的內容。如果你使用UTF-8,你可能已經損壞了消息......(ISO-8859-1,又名Latin-1實際上會工作,因爲它是單字節編碼)。

除此之外,您可以使用protobuf以及JMS上的任何其他格式。我更喜歡JSON的可讀性和可擴展性,但如果您已經使用protobuf,並且這是內部系統(而不是暴露給外部方),protobuf也可以。