자바 연결 MQ 의 인 스 턴 스

2811 단어 MQ
package cjf.mq.mqclient;


import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
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;
import com.ibm.mq.MQGetMessageOptions;

public class MQClient {

	static MQQueueManager qMgr;
	static int CCSID = 1381;//WINGBK,1208:UTF-8
	static String queueString = "MQ_QUEUE";

	public static void connect() throws MQException {
		MQEnvironment.hostname = "";
		MQEnvironment.channel = "java.channel";
		MQEnvironment.port = 1321;
		MQEnvironment.CCSID = CCSID;

		qMgr = new MQQueueManager("MQ_TEST");
		qMgr.disconnect();
	}

	public static void sendMsg(String msgStr) {
		int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT
				| MQC.MQOO_INQUIRE;
		MQQueue queue = null;
		try {
			//   Q1     
			queue = qMgr
					.accessQueue(queueString, openOptions, null, null, null);
			MQMessage msg = new MQMessage();//         
			msg.format = MQC.MQFMT_STRING;
			msg.characterSet = CCSID;
			msg.encoding = CCSID;
			// msg.writeObject(msgStr); //          
			msg.writeString(msgStr);
			MQPutMessageOptions pmo = new MQPutMessageOptions();
			msg.expiry = -1; //         
			queue.put(msg, pmo);//        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (queue != null) {
				try {
					queue.close();
				} catch (MQException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void receiveMsg() {
		int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT
				| MQC.MQOO_INQUIRE;
		MQQueue queue = null;
		try {
			queue = qMgr
					.accessQueue(queueString, openOptions, null, null, null);
			System.out.println("         :" + queue.getCurrentDepth());
			System.out.println("===========================");
			int depth = queue.getCurrentDepth();
			//            
			while (depth-- > 0) {
				MQMessage msg = new MQMessage();//         
				MQGetMessageOptions gmo = new MQGetMessageOptions();
				queue.get(msg, gmo);
				
				System.out.println("      :" + msg.getDataLength());
				System.out.println("     :
" + msg.readLine()); System.out.println("---------------------------"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (queue != null) { try { queue.close(); } catch (MQException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void main(String[] args) throws MQException { connect(); sendMsg("fuck MQ"); receiveMsg(); } }

좋은 웹페이지 즐겨찾기