我建议压缩有效负载并使用ByteMessage。消息属性可用于限定有效负载类型,类似于 HTTP,例如“内容编码”、“内容类型”
String payload = ...; // the xml
Session session = ...;
BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.writeBytes(compressGZIP(payload, StandardCharsets.UTF_8));
bytesMessage.setStringProperty("Content-Encoding", "gzip");
bytesMessage.setStringProperty("Content-Type", "text/xml; charset=utf-8");
这里是compressGZIP方法:
private byte[] compressGZIP(String string, Charset charset) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (GZIPOutputStream out = new GZIPOutputStream(byteArrayOutputStream)) {
StringReader stringReader = new StringReader(string);
// IOUtils from apache commons-io
IOUtils.copy(stringReader, out, charset);
}
return byteArrayOutputStream.toByteArray();
}
然后消费者可以根据“Content-Encoding”和“Content-Type”消息属性请求消息属性,解压并重新创建xml。
类似的东西
public void onMessage(Message message) {
BytesMessage bytesMessage = (BytesMessage) message;
long bodyLength = bytesMessage.getBodyLength();
byte[] rawPayload = new byte[(int) bodyLength];
InputStream payloadInputStream = new ByteArrayInputStream(rawPayload);
String contentEncoding = bytesMessage.getStringProperty("Content-Encoding");
if("gzip".equals(contentEncoding)) {
payloadInputStream = new GZIPInputStream(payloadInputStream);
}
String contentType = bytesMessage.getStringProperty("Content-Type");
MimeType mimeType = new MimeType(contentType); // from javax.activation
if("text".equals(mimeType.getPrimaryType())) {
if("xml".equals(mimeType.getSubType())) {
Charset charset;
String charsetString = mimeType.getParameter("charset");
if(charsetString != null) {
charset = Charset.forName(charsetString);
} else {
charset = StandardCharsets.UTF_8; // default
}
Reader reader = new InputStreamReader(payloadInputStream, charset);
String xml = IOUtils.toString(reader);
IOUtils.closeQuietly(reader);
}
}
}
此解决方案的优点是您可以使用标准 JMS api,而不是使用提供程序特定的配置。
缺点是发送方和接收方必须实现内容类型处理。
因此,您必须在可移植性和实施工作之间做出决定。