java 将 XML 发送到 JMS 时,我应该使用 TextMessage 还是 BytesMessage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10849828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:50:08  来源:igfitidea点击:

When sending XML to JMS should I use TextMessage or BytesMessage

javaxmlserializationcharacter-encodingjms

提问by Spence

I have found some quite conflicting information on the web and I think that each different JMS provider may also alter the answer too.

我在网上发现了一些非常矛盾的信息,我认为每个不同的 JMS 提供者也可能会改变答案。

I'm trying to understand when sending XML into a JMS system (e.g. ActiveMQ) whether I should use a

我试图了解在将 XML 发送到 JMS 系统(例如 ActiveMQ)时是否应该使用

  • BytesMessage : I can guarantee that the XML is serialized correctly and the preamble will match the actual encoding. Furthermore I can be sure that the client will be able to get the raw representation correctly.

  • TextMessage : There are APIs in many of the queue implementations for sending XML easily. I also understand that there are "encoding" information attached to the messages. But I risk encoding the message (and writing it's preamble) in one format and receiving it as another.

  • BytesMessage :我可以保证 XML 被正确序列化并且前导码将匹配实际编码。此外,我可以确定客户端将能够正确获取原始表示。

  • TextMessage :许多队列实现中都有用于轻松发送 XML 的 API。我也知道消息中附有“编码”信息。但是我冒着以一种格式对消息进行编码(并编写它的序言)并将其作为另一种格式接收的风险。

Does anyone have a definitive answer, or at least some reasons why you would choose one over the other?

有没有人有明确的答案,或者至少有一些为什么你会选择一个而不是另一个的原因?

回答by Lukas Eder

I agree with jos'comment to your question. First off, you should choose the kind of message type that best expresses the semanticsof your content. Reading the TextMessageJavadoc, I'd go for that:

我同意乔斯对你的问题评论。首先,您应该选择最能表达内容语义的消息类型。阅读TextMessageJavadoc,我会这样做:

This message type can be used to transport text-based messages, including those with XML content.

此消息类型可用于传输基于文本的消息,包括具有 XML 内容的消息。

So if you do run into trouble with your text message encoding, then there's probably some mis-configuration on the client / server side. But that shouldn't be a motivation for abusing a different message type that was not primarily intended for text transfer, such as BytesMessage.

因此,如果您确实遇到了文本消息编码问题,那么客户端/服务器端可能存在一些错误配置。但这不应成为滥用主要不是用于文本传输的不同消息类型的动机,例如BytesMessage.

N.B: Even with BytesMessage, you can get the encoding wrong. Imagine:

注意:即使使用BytesMessage,您也可能会弄错编码。想象:

// Send that data through JMS
byte[] data1 = "source text".getBytes("ISO-8859-1");

// Receive the byte stream on the other side. Ooops
String data2 = new String(data1, "UTF-8");