IBM MQ 9.1 教程二:Java代码访问本地队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013231970/article/details/85772963

1.导入MQ访问jar包

可通过maven导入所需jar包

<dependency>
    <groupId>com.ibm.mq</groupId>
    <artifactId>com.ibm.mq.allclient</artifactId>
    <version>9.1.0.0</version>
</dependency>

2. 代码分析

运行条件:代码要运行在安装IBM MQ的机器上

首先根据队列管理器名字创建一个队列管理器

MQQueueManager qMgr = new MQQueueManager(qManager);

创建队列连接

int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT;

MQQueue queue = qMgr.accessQueue(qName, openOptions);

发送消息:通过队列put方法发送消息

MQMessage msg = new MQMessage();
     
msg.writeUTF("Hello, World,我想去看看!");

MQPutMessageOptions pmo = new MQPutMessageOptions();

queue.put(msg, pmo);

接收消息:

MQMessage rcvMessage = new MQMessage();

MQGetMessageOptions gmo = new MQGetMessageOptions();

queue.get(rcvMessage, gmo);

以上只说明主要代码,详细代码参考代码示例

3. 代码示例

package com.ibmmq.demo.normal;

import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;

public class MQLocal {

  private static final String qManager = "QM_LOCAL";
  private static final String qName = "Q1";

  public static void main(String args[]) {
    try {
      MQQueueManager qMgr = new MQQueueManager(qManager);

      // 设置打开队列时的选项
      int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT;

      MQQueue queue = qMgr.accessQueue(qName, openOptions);

      // 定义一个消息对象
      MQMessage msg = new MQMessage();
      msg.writeUTF("Hello, World,我想去看看!");

      // 设置放入消息时的选项
      MQPutMessageOptions pmo = new MQPutMessageOptions();

      // 放入消息
      queue.put(msg, pmo);

      // 定义一个接受消息的对象
      MQMessage rcvMessage = new MQMessage();

      // 设置获得消息时的选项
      MQGetMessageOptions gmo = new MQGetMessageOptions();

      queue.get(rcvMessage, gmo);

      String msgText = rcvMessage.readUTF();
      System.out.println("获取消息: " + msgText);

      // 关闭队列
      queue.close();

      qMgr.disconnect();
    }
    catch (MQException ex) {
      System.out.println("An IBM MQ Error occurred : Completion Code " + ex.completionCode
          + " Reason Code " + ex.reasonCode);
      ex.printStackTrace();
      for (Throwable t = ex.getCause(); t != null; t = t.getCause()) {
        System.out.println("... Caused by ");
        t.printStackTrace();
      }

    }
    catch (java.io.IOException ex) {
      System.out.println("An IOException occurred whilst writing to the message buffer: " + ex);
    }
    return;
  }
}

猜你喜欢

转载自blog.csdn.net/u013231970/article/details/85772963