Apache Camel - Hazelcast主题发布/订阅 - 如何序列化订阅服务器中的字符串消息

时间:2015-11-13 02:02:43

标签: java apache-camel hazelcast

我试图按照http://camel.apache.org/hazelcast-component.html#HazelcastComponent-topic上的示例代码通过Hazelcast测试发布/订阅。

下面列出了发布者和订阅者路由定义

<route>
    <from uri="direct:inbound" />
    <setHeader headerName="CamelHazelcastOperationType">
        <simple>${type:org.apache.camel.component.hazelcast.HazelcastConstants.PUBLISH_OPERATION}</simple>
    </setHeader>
    <to uri="hazelcast:topic:foo" />
</route>    

<route>
    <from uri="hazelcast:topic:foo" />
    <log message="from hazelcast topic:= ${body}" />
    <bean ref="inboundProcessor" method="processHazelcastMsg" />
</route>

在我测试期间,我发送了一个字符串,如&#34; {\&#34;结果\&#34;:\&#34; InboundProcessor.processRequest成功\&#34;}&#34;发布者路由直接:入站端点。订户路由能够从主题接收消息并传递给处理器bean。但是,我没能正确收回字符串......

以下是我实现bean方法的方法

public void processHazelcastMsg(Exchange inEx) throws Exception{

    Map<String, Object> headers = inEx.getIn().getHeaders();

    System.out.println("Exchange > In msg > Body = " + inEx.getIn().getBody());
    System.out.println("Exchange > In msg > Body class = " + ObjectHelper.className(inEx.getIn().getBody()));
    DataAwareMessage msg = inEx.getIn().getBody(DataAwareMessage.class);

    byte[] b = serializeObject(msg.getMessageObject());
    String msgStr = new String(b, Charset.forName("utf-8"));

    System.out.println("Received msg string = " + msgStr);
}

private static byte[] serializeObject(Object object) throws IOException
{
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutput out = new ObjectOutputStream(bos)) {
            out.writeObject(object);
            return bos.toByteArray();
        } 
}   

这是日志输出:

[  hz._hzInstance_1_dev.event-5] route4                         INFO  from hazelcast topic:= com.hazelcast.topic.impl.DataAwareMessage[source=foo]
Exchange > In msg > Body = com.hazelcast.topic.impl.DataAwareMessage[source=foo]
Exchange > In msg > Body class = com.hazelcast.topic.impl.DataAwareMessage
Received msg string = ��

我确实尝试使用不同的编码来转换字符串(如UTF-8 / UTF-16等),但仍然失败了。想知道是否应该有另一种方法来取回订阅者中正确的字符串

1 个答案:

答案 0 :(得分:1)

使用hazelcast主题生成器,消息正文类型为Message。您可以通过调用Message.getMessageObject()来获取原始对象  :

public void processHazelcastMsg(Exchange inEx) throws Exception {
  String msgStr = inEx.getIn().getBody(Message.class).getMessageObject().toString();
}