我的代码正在监听 IBM MQ。接收 JMS BytesMessage,将其转换为接收器类中的字符串,并将相同的 JMS BytesMessage 传递到另一个处理器类。处理器类再次将其转换为字符串。接收器类和处理器类都使用如下相同的代码从 BytesMessage 获取字符串。我在 Receiver 类中获取了正确的字符串,但是当尝试从 Processor 类中的 BytesMessage 获取字符串时,它返回空字符串。请告知除了保留 JMS BytesMessage 之外还必须做什么,以便它也能在 Processor 类中转换为 String。
向处理器发送消息的代码:
String strMessage = null;
strMessage = getStringFromMessage(Message message)
process(message)
用于字符串转换的代码:
if (message instanceof BytesMessage){
BytesMessage byteMessage = (BytesMessage) message;
byte[] byteData = null;
byteData = new byte[(int) byteMessage.getBodyLength()];
byteMessage.readBytes(byteData);
stringMessage = new String(byteData);
}
我找到了解决方案。我在第一次阅读消息后添加了以下代码
byteMessage.reset()
这已将光标位置重置到开头,因此我能够在处理器中读取它。所以我在接收器中的最终代码如下所示
if (message instanceof BytesMessage){
BytesMessage byteMessage = (BytesMessage) message;
byte[] byteData = null;
byteData = new byte[(int) byteMessage.getBodyLength()];
byteMessage.readBytes(byteData);
byteMessage.reset();
stringMessage = new String(byteData);
}
再次读取它的原因是我开始在接收器中读取它以执行一些恢复功能。我想在不触及框架的情况下实现它。初始框架是仅在处理器中读取消息。
@Shankar Anand 的答案会起作用,但是,我想重构代码以适应它到底需要做什么
public String readIbmMqMessageAsString(BytesMessage message) throws JMSException, UnsupportedEncodingException {
message.reset(); //Puts the message body in read-only mode and repositions the stream of bytes to the beginning
int msgLength = ((int) message.getBodyLength());
byte[] msgBytes = new byte[msgLength];
message.readBytes(msgBytes, msgLength);
String encoding = message.getStringProperty(JMS_IBM_CHARACTER_SET);
return new String(msgBytes, encoding).trim();
}
message.reset()
应该发生在实际阅读消息之前。更简单的方法: byte[] buf=byteMessage.getBody(byte[].class);