假設:MQ已經安裝,並有可用的Queue Manager。
1、定義Channel和Queue
step 1 telnet到mq主機,並進入到../mqm/bin目錄下,運行runmqsc
step 2 運行DEFINE CHANNEL(CHL_WAS_STUDY) CHLTYPE(SVRCONN) ,創建Channel
step 3 運行DEFINE QLOCAL(Q_WAS_STUDY) ,創建Queue
2、Java Application代碼。Test.java
package com.leo.mq;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
public class Test {
private static final String QUEUE_MANAGER_NAME = "QM_1";
private static final String QUEUE_NAME = "Q_WAS_STUDY";
private static final String CHANNEL_NAME = "CHL_WAS_STUDY";
private static final String HOST_NAME = "192.168.0.10";
private static final int PORT = 1414;
private static final String USER_ID = "mqm";
private static final String PASSWORD = "password";
public Test(){
MQEnvironment.hostname = HOST_NAME;
MQEnvironment.channel = CHANNEL_NAME;
MQEnvironment.port = PORT;
MQEnvironment.userID = USER_ID;
MQEnvironment.password = PASSWORD;
MQEnvironment.CCSID=819;
// MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Test test = new Test();
test.send();
test.get();
}catch(Exception e){
e.printStackTrace();
}
}
private void send() throws Exception{
MQQueueManager manager = new MQQueueManager("QM_1");
int openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
MQQueue queue = manager.accessQueue(QUEUE_NAME,openOptions,null,null,null);
MQPutMessageOptions pmo = new MQPutMessageOptions();
MQMessage outMsg = new MQMessage();
outMsg.format = MQC.MQFMT_STRING;
String msgString = "Test Message from PtpSender program ";
outMsg.writeString(msgString);
queue.put(outMsg, pmo);
manager.commit();
System.out.println(" The message has been Successfully put!/n");
}
private void get() throws Exception{
MQQueueManager manager = new MQQueueManager("QM_1");
int openOptions = MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING;
MQQueue queue = manager.accessQueue(QUEUE_NAME,openOptions,null,null,null);
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options = gmo.options + MQC.MQGMO_SYNCPOINT;
gmo.options = gmo.options + MQC.MQGMO_WAIT;
gmo.options = gmo.options + MQC.MQGMO_FAIL_IF_QUIESCING;
gmo.waitInterval = 3000;
MQMessage inMsg = new MQMessage();
queue.get(inMsg, gmo);
String msgString = inMsg.readString(inMsg.getMessageLength());
System.out.println(" The Message from the Queue is : " + msgString);
manager.commit();
queue.close();
manager.disconnect();
}
}