【问题标题】:Convert JMS BytesMessage to String in java and use the same bytesmessage in another process在java中将JMS BytesMessage转换为String并在另一个进程中使用相同的bytesmessage
【发布时间】:2017-01-26 07:59:27
【问题描述】:

我的代码正在侦听 IBM MQ。接收 JMS BytesMessage,将其转换为接收器类中的字符串,并将相同的 JMS BytesMessage 传递给另一个处理器类。处理器类再次将其转换为字符串。接收器类和处理器类都使用如下相同的代码从 BytesMessage 获取字符串。我在 Receiver 类中获得了正确的字符串,但是当尝试从 Processor 类中的 BytesMessage 获取字符串时,它返回空字符串。请告知除了保留 JMS BytesMessage 之外还需要做什么,以便它也可以在处理器类中转换为字符串。

向处理器发送消息的代码:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,readBytes 方法在内部缓冲区中推进光标。如果必须再次阅读该消息,则必须将其重置。否则会抛出带有“文件结束”的 JMSException。
    • 那里的代码...为什么要在阅读后重置光标?从获取数据的任务的角度来看,这是完全没有必要的。这个答案令人困惑,应该重写......
    • 是的,我同意 zordid,reset() 应该发生在 read 方法之前
    【解决方案2】:

    @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. 当我们从字节创建字符串时,最好提供编码字符集,该字符集用于将消息转换为再见
    4. 我们可能不需要额外的尾随空格。在这种情况下,您也可以对其进行修剪。
    5. 我把异常抛给父方法处理

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2010-11-16
      • 2011-07-10
      • 2015-04-20
      • 2012-06-06
      • 1970-01-01
      • 2015-10-12
      • 2018-10-08
      相关资源
      最近更新 更多