当应用程序和MQ不在同一台主机上的时候,我们将要通过通道去访问;
1.创建队列管理器时勾选创建服务器链接通道;

2.创建一个本地队列
命名为Q1
3.创建通道
右击通道->新建->服务器链接通道
命名为SERVERQM2
4.代码示例调用
package com.ibmmq.util.mqutil;import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;public class MqDemo {private MQQueueManager qMgr;private MQQueue sendQueue;private MQQueue receiveQueue;private static int CCSID = 1381;//编码字符标识,通道-属性-常规private static String hostname = "192.168.31.239";int port = 1415;static String queueManagerName = "QM_2";static String queueName = "Q1";static String channel = "SERVERQM2";static String userId = "administrator";static String password = "zcy123456";public MqDemo() throws MQException {MQEnvironment.hostname = hostname;MQEnvironment.port = port;MQEnvironment.channel = channel;MQEnvironment.CCSID = CCSID;MQEnvironment.userID = userId; //MQ中拥有权限的用户名MQEnvironment.password = password; //用户名对应的密码qMgr = new MQQueueManager(queueManagerName);//创建队列管理器}public void sendMsg(String msgStr) {int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT | MQConstants.MQOO_INQUIRE;try {// 建立通道的连接sendQueue = qMgr.accessQueue(queueName, openOptions, null, null, null);MQMessage msg = new MQMessage();// 要写入队列的消息msg.format = MQConstants.MQFMT_STRING;msg.characterSet = CCSID;msg.encoding = CCSID;msg.writeUTF(msgStr);MQPutMessageOptions pmo = new MQPutMessageOptions();msg.expiry = -1; // 设置消息永不过期sendQueue.put(msg, pmo);// 将消息放入队列qMgr.disconnect();} catch (Exception e) {e.printStackTrace();} finally {if (sendQueue != null) {try {sendQueue.close();} catch (MQException e) {e.printStackTrace();}}}}public void receiveMsg() {int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT | MQConstants.MQOO_INQUIRE;try {receiveQueue = qMgr.accessQueue(queueName, openOptions, null, null, null);int depth = receiveQueue.getCurrentDepth();System.out.println("该队列当前的深度为:" + depth);// 将队列的里的消息读出来while (depth-- > 0) {MQMessage rcvMessage = new MQMessage();// 要读的队列的消息MQGetMessageOptions gmo = new MQGetMessageOptions();receiveQueue.get(rcvMessage, gmo);String msgText = rcvMessage.readUTF();System.out.println("消息的内容:" + msgText);}} catch (Exception e) {e.printStackTrace();} finally {if (receiveQueue != null) {try {receiveQueue.close();} catch (MQException e) {e.printStackTrace();}}try {qMgr.disconnect();} catch (MQException e) {e.printStackTrace();}}}public static void main(String[] args) throws MQException {new MqDemo().sendMsg("我是第一条消息");new MqDemo().sendMsg("我是第二条消息");new MqDemo().receiveMsg();}
}
5.常见问题
完成代码为“2”,原因为“2058” MQ远程队列的名称 错误
完成代码为“2”,原因为“2540” 服务器连接的通道 错误
完成代码为“2”,原因为“2018” 未连接至队列管理器。
完成代码为“2”,原因为“2035” 权限错误(用户密码错误也会报2035)
右击QM_2-属性-通信-通道认证记录修改为已禁用;