在java中将JMS BytesMessage转换为String并在另一个进程中使用相同的bytesmessage

问题描述 投票:0回答:3

我的代码正在监听 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);
}
java string jms
3个回答
9
投票

我找到了解决方案。我在第一次阅读消息后添加了以下代码

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);
}

再次读取它的原因是我开始在接收器中读取它以执行一些恢复功能。我想在不触及框架的情况下实现它。初始框架是仅在处理器中读取消息。


1
投票

@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();
    }

  1. 在读取消息之前,我们需要将字节流重新定位到开头。因此
    message.reset()
    应该发生在实际阅读消息之前。
  2. 然后我们可以读取消息并将其放入字节数组中
  3. 当我们从字节创建字符串时,最好提供编码字符集,该字符集用于将消息转换为bye
  4. 我们可能不需要额外的尾随空格。在这种情况下,您也可以修剪它。
  5. 我将异常抛给父方法来处理

0
投票

更简单的方法: byte[] buf=byteMessage.getBody(byte[].class);

© www.soinside.com 2019 - 2024. All rights reserved.