Apache Camel -- Hazelcast 主题 Publish/Subscribe -- 如何在订阅者中序列化字符串消息

Apache Camel -- Hazelcast Topic Publish/Subscribe -- how to serialize String message in Subscriber

我试图按照 http://camel.apache.org/hazelcast-component.html#HazelcastComponent-topic 中的示例代码通过 Hazelcast 使用 publish/subscribe 进行测试。

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

<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>

在测试期间,我通过 direct:inbound 端点向发布者路由发送了一个类似“{\"result\": \"InboundProcessor.processRequest success\"}”的字符串。订阅者路由能够从主题接收消息并传递给处理器 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... 等)来隐藏字符串,但仍然失败。想知道是否应该有另一种方法来取回 subscriber

中的正确字符串

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

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