public class MQConnector
{
protected String qManager = ""; // define name of queue manager
protected String qManagerHost = "";
protected String queuName = ""; // define name of queue
protected MQQueue mqQueue;
protected MQQueueManager qMgr;
public static boolean DEBUG = true;
public MQConnector()
{
}
public void initMq()
{
try
{
FileInputStream fis = new FileInputStream(new File("mqconnect.properties"));
Properties props = new Properties();
props.load(fis);
fis.close();
qManager = props.getProperty("queue.manager");
qManagerHost = props.getProperty("queue.manager.host");
queuName = props.getProperty("queue.name");
// Create a connection to the queue manager
MQEnvironment.channel = "SYSTEM.DEF.SVRCONN";
MQEnvironment.hostname = qManagerHost;
debug("Connecting to QueueManager " + qManager + " on " + qManagerHost);
qMgr = new MQQueueManager(qManager);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void openQueue() throws MQException
{
// Set up the options on the queue we wish to open...
// Note. All WebSphere MQ Options are prefixed with MQC in Java.
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;
// Now specify the queue that we wish to open,
// and the open options...
debug("Opening queue: " + queuName);
try
{
mqQueue = qMgr.accessQueue(queuName, openOptions);
}
catch(MQException mqe)
{
//check if MQ reason code 2045
//means that opened queu is remote and it can not be opened as
//input queue
//try to open as output only
if(mqe.reasonCode==2045)
{
openOptions = MQC.MQOO_OUTPUT;
mqQueue = qMgr.accessQueue(queuName, openOptions);
}
}
}
MQPutMessageOptions pmo = new MQPutMessageOptions();
MQMessage mqMsg = new MQMessage();
mqMsg.write(msg.getBytes());
// put the message on the queue
mqQueue.put(mqMsg, pmo);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public String getMessageFromQueue() throws MQException
{
try
{
MQMessage mqMsg = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
// Get a message from the queue
mqQueue.get(mqMsg,gmo);
//Extract the message data
int len=mqMsg.getDataLength();
byte[] message = new byte[len];
mqMsg.readFully(message,0,len);
return new String(message);
}
catch(MQException mqe)
{
int reason=mqe.reasonCode;
mqm@wmq1:~/bin> ./mqsend "This is test message" This is another message
MQJE001: Completion Code 2, Reason 2045
Message sent.
Message sent.
Message sent.
Message sent.
Message sent.
接收消息与上面所示的 mqget 命令相同。以下代码说明了如何接收多个消息:
mqm@wmq2:~/bin> ./mqget
This is test message
mqm@wmq2:~/bin> ./mqget
This
mqm@wmq2:~/bin> ./mqget
is
mqm@wmq2:~/bin> ./mqget
another
mqm@wmq2:~/bin> ./mqget
message
mqm@wmq2:~/bin> ./mqget
MQJE001: Completion Code 2, Reason 2033
下一个示例将发送所有 Java 文件的内容:
mqm@wmq1:~/bin> ls -1 mqconn/*.java | awk '{print "mqsend -f """}' | sh 2> /dev/null
Message sent.
Message sent.
Message sent.