gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:54:40 25 4
gpt4 key购买 nike

我试图遵循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...等)来隐藏字符串,但仍然失败。想知道是否应该有另一种方法来获取订阅者中的正确字符串

最佳答案

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

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

关于java - Apache Camel -- Hazelcast 主题发布/订阅 -- 如何在订阅者中序列化字符串消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33684796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com