Java 路由中的Apache Camel自动类型转换协议
我使用Camel和ActiveMQ设置了一个主题,它将消息作为protobuf的字节数组接收 接收路由如下所示:Java 路由中的Apache Camel自动类型转换协议,java,apache-camel,protocol-buffers,Java,Apache Camel,Protocol Buffers,我使用Camel和ActiveMQ设置了一个主题,它将消息作为protobuf的字节数组接收 接收路由如下所示: <route> <from uri="jmsComponent:topic:{{heartbeat}}" /> <unmarshal> <protobuf instanceClass="protobuf.HeartbeatProto" /> </unm
<route>
<from uri="jmsComponent:topic:{{heartbeat}}" />
<unmarshal>
<protobuf instanceClass="protobuf.HeartbeatProto" />
</unmarshal>
<to uri="bean:heartbeatConsumer" />
</route>
heartbeatConsumer只有一个方法采用POJO版本的心跳。为了实现这一点,我有一个类型转换器,可以将POJO转换为protobuf,或者从POJO转换为protobuf
这非常有效,Camel能够获取字节数组并将其作为POJO传递给heartbeatConsumer
我的问题来自发件人。我的发送路线设置为:
<route>
<from uri="quartz2://heartbeatJob?cron=0/30+*+*+*+*+?" />
<to uri="bean:heartbeat?method=sendHeartbeat" />
<marshal>
<protobuf instanceClass="protobuf.HeartbeatProto" />
</marshal>
<to uri="jmsComponent:topic:{{heartbeat}}" />
</route>
这给了我一个例外:
'java.lang.ClassCastException:protobuf.HeartbeatProto无法转换为com.google.protobuf.Message'
为什么它能够在接收路由中自动键入转换器,但不在发送路径中?将Java类编组到protobuf有效负载仅适用于实现com.google.protobuf.Message接口的Java类,如org.apache.camel.dataformat.protobuf.ProtobufDataFormat的源代码所示:
如中所述,您应该从一个.proto定义文件开始,该文件是用protoc-java_out=.编译的/将protobuf.HeartbeatProto转换为实现所需接口的Java类。我认为这不是实现接口的问题。Mike Fisher似乎有一个问题,sendHeartbeat方法返回一个POJO,他为此编写了一个类型转换器,例如类Heartbeat到类HeartbeatProto实现com.google.protobuf.Message。Camel的类型转换器系统不应该知道输入是心跳对象,输出需要是HeartbeatProto实现com.google.protobuf.Message对象并为您进行类型转换吗?如果HeartbeatProto实现接口消息,我们就不会看到ClassCastException。实现消息看起来像太过分了。sendHeartbeat正在返回一个POJO,其中Camel有一个TypeConverter,可以从POJO转换为实现消息的对象。在本例中,protobuf.HeartbeatProto.@thpatel是的,您是对的,实现消息似乎有些过分。但是,我看不到其他解决方案。
public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
((Message)graph).writeTo(outputStream); // <- here the ClassCastException occurs!
}