IBM MQ 学习、应用

 

 

MQ应用程序的开发,简单的实现一下关键的发送消息和接收消息的操作.首先做简单的准备工作,建队列管理器QM1,在QM1中建队列Q1,然后在高级中建立通道BICASHY,类型为服务器连接通道,端口号1414,这里做最简单的配置,死信、传输队列及远程队列都暂时不建。。。
:如果建另一个队列管理器QM2,其侦听端口一定不能和1414重复。

package com.wondertek.flow.test;   
  
import java.io.IOException;   
  
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;   
  
public class MQManager {   
  
    private MQQueueManager qMgr;   
  
    private void getConnMQmanager() {   
        MQEnvironment.hostname = "77.20.17.15";// MQ服务器IP   
        MQEnvironment.channel = "BICASHY";     // 队列管理器对应的服务器连接通道   
        MQEnvironment.CCSID = 1381;            // 字符编码   
        MQEnvironment.port = 1414;             // 队列管理器的端口号   
        try {   
            qMgr = new MQQueueManager("QM1");// 队列管理器名称   
        } catch (MQException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
    }   
  
    private void closeConnMQmanager() {   
        if (qMgr != null) {   
            try {   
                qMgr.close();   
            } catch (MQException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            }   
        }   
    }   
  
    public 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("Q1", openOptions, null, null,null);     
            MQMessage msg = new MQMessage();// 要写入队列的消息   
            msg.format = MQC.MQFMT_STRING;   
            msg.characterSet = 1381;   
            msg.writeObject(msgStr); //将消息写入消息对象中   
            MQPutMessageOptions pmo = new MQPutMessageOptions();   
            msg.expiry = -1;    // 设置消息用不过期   
            queue.put(msg, pmo);// 将消息放入队列   
        } catch (MQException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        } catch (IOException 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 void receiveMsg()   
    {   
        int openOptions = MQC.MQOO_INPUT_AS_Q_DEF|MQC.MQOO_OUTPUT|MQC.MQOO_INQUIRE;   
        MQQueue queue = null;   
        try {   
            queue = qMgr.accessQueue("Q1", 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("消息的内容:/n"+msg.readObject());   
                System.out.println("---------------------------");   
            }   
        } catch (MQException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        } 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) {   
        MQManager mm = new MQManager();   
        mm.getConnMQmanager();   
        try {   
            mm.sendMsg("第一条测试信息");   
            mm.sendMsg("test第二条测试信息");   
            mm.receiveMsg();   
        } catch (Exception e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
        mm.closeConnMQmanager();   
    }   
}  

IBM MQ Series发送消息和读取消息(use JAVA)

关键字: code
MQSender .java
向IBM MQ发送消息
import java.io.IOException;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

public class MQSender implements Runnable {
	private static final String MQ_MANAGER = "MQ_TEST";
	private static final String MQ_HOST_NAME = "192.168.0.1";
	private static final String MQ_CHANNEL = "TEST";
	private static final String MQ_QUEUE_NAME = "TEST_QUEUE";
	private static final int MQ_PROT = 8100;
	private static final int MQ_CCSID = 819;

	public void run() {
		MQQueueManager mqQueueManager = null;
		MQQueue mqQueue = null;
		try {
			MQEnvironment.addConnectionPoolToken();
			MQEnvironment.hostname = MQ_HOST_NAME;
			MQEnvironment.channel = MQ_CHANNEL;
			MQEnvironment.port = MQ_PROT;
			MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES);
			MQEnvironment.CCSID = MQ_CCSID;
			int sendOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
			mqQueueManager = new MQQueueManager(MQ_MANAGER);
			mqQueue = mqQueueManager.accessQueue(MQ_QUEUE_NAME, sendOptions, null, null, null);
			MQPutMessageOptions mqPutMessageOptions = new MQPutMessageOptions();
			MQMessage mqMessage = null;
			String putMessage = "test";
			mqMessage = new MQMessage();
			mqMessage.format = MQC.MQFMT_STRING;
			mqMessage.write(putMessage.getBytes());
			mqQueue.put(mqMessage, mqPutMessageOptions);
		} catch (MQException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (mqQueue != null) {
				try {
					mqQueue.close();
				} catch (MQException e) {
					e.printStackTrace();
				}
			}
			if (mqQueueManager != null) {
				try {
					mqQueueManager.close();
				} catch (MQException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String arg[]) {
		MQSender client = new MQSender();
		Thread mqClientThread = new Thread(client);
		mqClientThread.start();
	}
}


MQReceiver.java 监听IBM MQ取回消息
import java.io.IOException;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

public class MQSender implements Runnable {
	private static final String MQ_MANAGER = "MQ_TEST";
	private static final String MQ_HOST_NAME = "192.168.0.1";
	private static final String MQ_CHANNEL = "TEST";
	private static final String MQ_QUEUE_NAME = "TEST_QUEUE";
	private static final int MQ_PROT = 8100;
	private static final int MQ_CCSID = 819;

	public void run() {
		MQQueueManager mqQueueManager = null;
		MQQueue mqQueue = null;
		try {
			MQEnvironment.addConnectionPoolToken();
			MQEnvironment.hostname = MQ_HOST_NAME;
			MQEnvironment.channel = MQ_CHANNEL;
			MQEnvironment.port = MQ_PROT;
			MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES);
			MQEnvironment.CCSID = MQ_CCSID;
			int sendOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
			mqQueueManager = new MQQueueManager(MQ_MANAGER);
			mqQueue = mqQueueManager.accessQueue(MQ_QUEUE_NAME, sendOptions, null, null, null);
			MQPutMessageOptions mqPutMessageOptions = new MQPutMessageOptions();
			MQMessage mqMessage = null;
			String putMessage = "test";
			mqMessage = new MQMessage();
			mqMessage.format = MQC.MQFMT_STRING;
			mqMessage.write(putMessage.getBytes());
			mqQueue.put(mqMessage, mqPutMessageOptions);
		} catch (MQException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (mqQueue != null) {
				try {
					mqQueue.close();
				} catch (MQException e) {
					e.printStackTrace();
				}
			}
			if (mqQueueManager != null) {
				try {
					mqQueueManager.close();
				} catch (MQException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String arg[]) {
		MQSender client = new MQSender();
		Thread mqClientThread = new Thread(client);
		mqClientThread.start();
	}
}

WebSphere MQ传输环境搭建和测试

关键字: 代码
作者:rainman2008

在“WebSphere MQ程序设计初探”一文中,讨论了从MQ队列管理器的本地队列中放置和读出消息的程序,本文主要通过两台机器,搭建MQ消息传输的环境,并编写测试程序进行测试。

    第一、准备工作
准备2台Win2000环境(XP也可),通过以太网连通。
机器A:代码为00000000,IP地址为:10.1.1.1
机器B:代码为88888888,IP地址为:10.1.1.2
安装MQ 5.3

    第二、创建MQ对象

    A机器上:
1、打开“WebSphere MQ资源管理器”,新建队列管理器,名称为QM_00000000,其余采用默认设置;
2、在QM_00000000队列管理器中创建本地队列,名称为LQ_00000000;
3、创建传输队列,名称为XQ_88888888(新建时选择“本地队列”,将“用法”设置为“传输”);
4、创建远程队列定义,名称为RQ_88888888,指定远程队列名称为LQ_88888888,远程队列管理器名称为QM_88888888,传输队列名称为XQ_88888888;
5、创建发送方通道,名称为00000000.88888888,传输协议为TCP/IP,连接名称为10.1.1.2(1414),传输队列为XQ_88888888;
6、创建接受方通道,名称为88888888.00000000,采用默认设置;
7、创建服务器连接通道,名称为DC.SVRCONN,采用默认设置(该通道主要给后面的测试程序使用)。

    B机器和A机器上的操作一样,只是命名不同,如下:
1、打开“WebSphere MQ资源管理器”,新建队列管理器,名称为QM_88888888,其余采用默认设置;
2、在QM_88888888队列管理器中创建本地队列,名称为LQ_88888888;
3、创建传输队列,名称为XQ_00000000(新建时选择“本地队列”,将“用法”设置为“传输”);
4、创建远程队列定义,名称为RQ_00000000,指定远程队列名称为LQ_00000000,远程队列管理器名称为QM_00000000,传输队列名称为XQ_00000000;
5、创建发送方通道,名称为88888888.00000000,传输协议为TCP/IP,连接名称为10.1.1.1(1414),传输队列为XQ_00000000;
6、创建接受方通道,名称为00000000.88888888,采用默认设置;
7、创建服务器连接通道,名称为DC.SVRCONN,采用默认设置。

    第三、消息测试

    在A、B机器上分别启动其发送方通道,正常情况通道状态应为“正在运行”。
通过如下测试程序进行测试,文件名为:MQTest.java,在机器A上进行运行(如在B上运行请读者自行适当修改)。
import java.io.IOException;
import java.util.Hashtable;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
public class MQSample{
//定义队列管理器和队列的名称 
private static String qmName = "QM_00000000";
private static String qName = "RQ_88888888";
private static MQQueueManager qMgr;
private static Hashtable properties = new Hashtable();
public static void main(String args[]) {
try {
properties.put("hostname", "10.1.1.1");
properties.put("port", new Integer(1414));
properties.put("channel", "DC.SVRCONN");
properties.put("CCSID", new Integer(1381));
properties.put("transport","MQSeries");
// Create a connection to the queue manager 
qMgr = new MQQueueManager(qmName,properties);
// Set up the options on the queue we wish to open... 
int openOptions = 16;
// Now specify the queue that we wish to open,
// and the open options... 
MQQueue remoteQ = qMgr.accessQueue(qName, openOptions);
// Define a simple WebSphere MQ message, and write some text in UTF format.. 
MQMessage putMessage = new MQMessage();
putMessage.writeUTF("Test");
// specify the message options... 
MQPutMessageOptions pmo = new MQPutMessageOptions();
// accept the defaults, same as MQPMO_DEFAULT
// put the message on the queue 
remoteQ.put(putMessage,pmo);
System.out.println("Message has been input into the Remote Queue");
// Close the queue... 
remoteQ.close();
// Disconnect from the queue manager 
qMgr.disconnect();
}catch (MQException ex) {
// If an error has occurred in the above, try to identify what went wrong
// Was it a WebSphere MQ error? 
System.out.println("A WebSphere MQ error occurred : Completion code " + ex.completionCode + " Reason code " + ex.reasonCode);
}catch (IOException ex) {
// Was it a Java buffer space error? 
System.out.println("An error occurred whilst writing to the message buffer: " + ex);
}catch(Exception ex){
ex.printStackTrace();
}
}
} 

运行程序后,请在B机器的本地队列LQ_88888888中检查是否有消息存在,如果有说明测试成功。读者可以自行编写把消息从对方的本地队列读取出来的程序。

一段同步接收和发送MQ消息的代码

 

 

 

 

 

 

 

=========================================

 

 

 

JAVA代码:
package com.sdb.payment.core.mq;    
   
import org.apache.log4j.Logger;    
   
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;    
   
public class MessageQueueService {    
    private static Logger logger = Logger.getLogger(MessageQueueService.class);    
   
    private String hostname = "192.168.0.117";    
   
    private String channel = "CHL.SVRCONN";    
   
    private String queueManager = "QM_SERVER";    
   
    private String sendQueue = "OMP.QRMT";    
   
    private String recvQueue = "OMP.QLCA";    
   
    private int port = 24100;    
   
    private int ccsid = 1381;    
   
    private int failedCount = 5;    
   
    private int intervalTime = 1000;    
   
    public MessageQueueService() {    
        MQEnvironment.hostname = hostname;    
        MQEnvironment.channel = channel;    
        MQEnvironment.CCSID = ccsid;    
        MQEnvironment.port = port;    
    }    
   
    public String send(String sendMsg) throws Exception {    
        MQQueueManager qManager = new MQQueueManager(queueManager);    
            
        // send message    
        int openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;    
        MQQueue sQueue = qManager.accessQueue(sendQueue, openOptions);    
        MQPutMessageOptions pmo = new MQPutMessageOptions();    
        MQMessage send = new MQMessage();    
        send.write(sendMsg.getBytes());    
        System.out.println("send message : " + sendMsg);    
        sQueue.put(send, pmo);    
        sQueue.close();    
        System.out.println("send message Id");    
        for (int i = 0; i<send.messageId.length; i++) {    
            System.out.print(send.messageId[i]);    
        }    
        System.out.println();    
        System.out.println("send message Id");    
        // fetch message    
        openOptions = MQC.MQOO_INQUIRE + MQC.MQOO_FAIL_IF_QUIESCING    
                + MQC.MQOO_INPUT_SHARED;    
        MQQueue rQueue = qManager.accessQueue(recvQueue, openOptions);    
        MQGetMessageOptions getOptions = new MQGetMessageOptions();    
        getOptions.options = MQC.MQGMO_WAIT;    
        getOptions.waitInterval = intervalTime;    
            
        MQMessage recvMsg = new MQMessage();    
        recvMsg.messageId = send.messageId;//这里是关键,要保持接收的msgid跟发送的msgid值是一样的,    
                                           //这样就会根据msgId来取队列的消息了,而不会取到别的消息    
        send.clearMessage();    
            
        boolean received = false;    
        int fetchCount = 0;    
        while (!received) {    
            try {    
                fetchCount++;    
                rQueue.get(recvMsg, getOptions);    
                //logger.debug("the " + fetchCount + " time fetch message!");    
                System.out.println("fetch message !!!");    
                received = true;    
            } catch (MQException me) {    
                if (me.reasonCode == MQException.MQRC_NO_MSG_AVAILABLE) {    
                    if (fetchCount > failedCount) {    
                        recvMsg.clearMessage();    
                        rQueue.close();    
                        qManager.disconnect();    
                        //logger.error("can't fetch message for " + me.getMessage());    
                        return null;    
                    }    
                }    
            } catch (Exception ex) {    
                recvMsg.clearMessage();    
                rQueue.close();    
                qManager.disconnect();    
                //logger.error("can't fetch message for " + ex.getMessage());    
                return null;    
            }    
        }    
            
        byte[] bMsg = new byte[recvMsg.getMessageLength()];    
        recvMsg.readFully(bMsg);    
        System.out.println("rec correlationId Id");    
        for (int i = 0; i<recvMsg.correlationId.length; i++) {    
            System.out.print(recvMsg.correlationId[i]);    
        }    
        System.out.println();    
        System.out.println("rec correlationId Id");    
        String recv = new String(bMsg);    
        recvMsg.clearMessage();    
        rQueue.close();    
            
        qManager.disconnect();    
            
        return recv;    
    }    
   
    public void setChannel(String channel) {    
        this.channel = channel;    
    }    
   
    public void setHostname(String hostname) {    
        this.hostname = hostname;    
    }    
   
    public void setQueueManager(String queueManager) {    
        this.queueManager = queueManager;    
    }    
   
    public void setPort(int port) {    
        this.port = port;    
    }    
   
    public void setIntervalTime(int intervalTime) {    
        this.intervalTime = intervalTime;    
    }    
   
    public void setFailedCount(int failedCount) {    
        this.failedCount = failedCount;    
    }    
   
    public void setRecvQueue(String recvQueue) {    
        this.recvQueue = recvQueue;    
    }    
   
    public void setSendQueue(String sendQueue) {    
        this.sendQueue = sendQueue;    
    }    
}   
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值