【问题标题】:Apache Camel -- Hazelcast Topic Publish/Subscribe -- how to serialize String message in SubscriberApache Camel -- Hazelcast 主题发布/订阅 -- 如何在订阅者中序列化字符串消息
【发布时间】:2016-03-07 04:39:24
【问题描述】:

我试图按照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>

在测试期间,我通过 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... 等)来转换字符串,但仍然失败。想知道是否应该有另一种方法来取回订阅者中的正确字符串

【问题讨论】:

    标签: java apache-camel hazelcast


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。您的 API 调用有效,但它返回一个类似“[B@78c3d9”的字符串,最后我发现我必须在"" 之前的路由定义,然后您的调用将返回原始字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2016-06-17
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多