IBM MQ 9.1 教程三:远程访问IBM MQ队列
2019年01月04日 14:43:48 可还记得你我的誓言 阅读数:34
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013231970/article/details/85774856
当应用程序不和IBM MQ的安装程序在一台主机上时,就需要通过IP远程访问IBM MQ队列了,此时可用TCP/IP协议
1. 在创建队列 管理器时,要勾选创建服务器连接通道
2. 创建一个本地队列Q1
3. 右键通道选项,新建服务器连接通道,名称SVRCONN.ONE
4. 代码访问示例,此示例访问windows上的IBM MQ,windows系统设置了用户名和密码
-
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.1.133"; -
int port = 1466; -
static String queueManagerName = "QM_2"; -
static String queueName = "Q1"; -
static String channel = "SVRCONN.ONE"; -
static String userId = "tiger"; -
static String password = "tiger"; -
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("消息1"); -
new MqDemo().sendMsg("消息2"); -
new MqDemo().sendMsg("消息3"); -
new MqDemo().receiveMsg(); -
} -
}