標籤:
前提:MQ伺服器端建立
隊列管理器:QueueManager
隊列:XML.IN
伺服器串連通道:SYSTEM.ADMIN.SVRCONN
監聽器監聽1414連接埠。
package 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;/** * 測試調用MQ * * @author Administrator * */public class TestMQ {/** * 隊列管理器 */private static final String MQ_QUEUE_MANAGER = "QueueManager";/** * 隊列 */private static final String MQ_QUEUE = "XML.IN";/** * 通道 */private static final String MQ_CHANNEL = "SYSTEM.ADMIN.SVRCONN";/** * IP */private static final String MQ_HOST = "localhost";/** * 連接埠 */private static final int MQ_PORT = 1414;private MQQueueManager qMgr;/** * 測試 * @param args */public static void main(String[] args) {TestMQ test = new TestMQ();test.getConnMQManager();test.sendMessage("1111111");test.receiveMsg();}/** * 發送訊息到MQ * @param message */public void sendMessage(String message) {MQQueue mqQueue = null;try {// 建立串連int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT| MQC.MQOO_INQUIRE;mqQueue = qMgr.accessQueue(MQ_QUEUE, openOptions, null, null, null);MQMessage msg = new MQMessage();msg.format = MQC.MQFMT_STRING;msg.characterSet = 1381;msg.writeObject(message);MQPutMessageOptions pmo = new MQPutMessageOptions();// 設定訊息用不到期msg.expiry = -1; // 將訊息放入隊列mqQueue.put(msg, pmo);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally{if(mqQueue!=null){try {mqQueue.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}}}/** * 讀取MQ訊息 */public void receiveMsg(){MQQueue mqQueue = null;try {// 建立串連int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT| MQC.MQOO_INQUIRE;mqQueue = qMgr.accessQueue(MQ_QUEUE, openOptions, null, null, null);// 隊列深度int depth = mqQueue.getCurrentDepth();System.out.println("當前隊列深度為:"+depth);while (depth-->0){// 要讀取的訊息MQMessage msg = new MQMessage();MQGetMessageOptions mqGet = new MQGetMessageOptions();mqQueue.get(msg, mqGet);System.out.println("訊息的大小為:"+msg.getDataLength());System.out.println("訊息的內容為:"+msg.readObject());}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally{if(mqQueue!=null){try {mqQueue.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}}}/** * 擷取串連 */public void getConnMQManager() {MQEnvironment.hostname = MQ_HOST;MQEnvironment.channel = MQ_CHANNEL;MQEnvironment.CCSID = 1381; // 字元編碼MQEnvironment.port = MQ_PORT;try {qMgr = new MQQueueManager(MQ_QUEUE_MANAGER);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}/** * 關閉串連 */public void closeConnMQManager() {if (qMgr != null) {try {qMgr.close();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}}
對於報以下錯誤的可參考http://www-01.ibm.com/support/docview.wss?uid=swg21636532
MQJE001:發生 MQException:完成碼 2,原因 2035
MQJE036:隊列管理器拒絕串連嘗試
MQJE001:完成碼 2,原因 2035
com.ibm.mq.MQException: MQJE001:完成碼 2,原因 2035
JAVA 調用MQ