* @modified by actorai E-mail:actorai@163.com
* @version 创建时间:2010-9-15
* 通过MQ API方式连接MQ;绑定服务器方式
* WebSphere MQ classes for Java的绑定模式与客户连接模式存在下列区别:
* 1 忽略了MQEnvironmnet类所提供的大多数参数。
* 2 绑定模式支持MQBEGIN和快速绑定。
* 类说明
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
MessageByMQ_Bind{
private
static
String qmName;
private
static
String qName;
private
static
MQQueueManager qMgr;
static
{
qmName =
"QM_APPLE"
;
qName =
"01"
;
try
{
qMgr =
new
MQQueueManager(qmName);
}
catch
(MQException e) {
System.out.println(
"初使化MQ出错"
);
e.printStackTrace();
* 往MQ发送消息
* @param message
* @return
public
static
int
sendMessage(String message){
int
result=
0
;
try
{
int
openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
if
(qMgr==
null
|| !qMgr.isConnected()){
qMgr =
new
MQQueueManager(qmName);
MQQueue queue = qMgr.accessQueue(qName, openOptions);
MQMessage putMessage =
new
MQMessage();
putMessage.writeUTF(message);
MQPutMessageOptions pmo =
new
MQPutMessageOptions();
queue.put(putMessage,pmo);
queue.close();
}
catch
(MQException ex) {
System.out.println(
"A WebSphere MQ error occurred : Completion code "
+ ex.completionCode +
" Reason code "
+ ex.reasonCode);
ex.printStackTrace();
}
catch
(IOException ex) {
System.out.println(
"An error occurred whilst writing to the message buffer: "
+ ex);
}
catch
(Exception ex){
ex.printStackTrace();
}
finally
{
try
{
qMgr.disconnect();
}
catch
(MQException e) {
e.printStackTrace();
return
result;
* 从队列中去获取消息,如果队列中没有消息,就会发生异常,不过没有关系,有TRY...CATCH,如果是第三方程序调用方法,如果无返回则说明无消息
* 第三方可以将该方法放于一个无限循环的while(true){...}之中,不需要设置等待,因为在该方法内部在没有消息的时候会自动等待。
* @return
public
static
String getMessage(){
String message=
null
;
try
{
int
openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;
MQMessage retrieve =
new
MQMessage();
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 =
1000
;
if
(qMgr==
null
|| !qMgr.isConnected()){
qMgr =
new
MQQueueManager(qmName);
MQQueue queue = qMgr.accessQueue(qName, openOptions);
queue.get(retrieve, gmo);
message = retrieve.readLine();
System.out.println(
"The message is: "
+ message);
queue.close();
}
catch
(MQException ex) {
System.out.println(
"A WebSphere MQ error occurred : Completion code "
+ ex.completionCode +
" Reason code "
+ ex.reasonCode);
}
catch
(IOException ex) {
ex.printStackTrace();
}
catch
(Exception ex){
ex.printStackTrace();
}
finally
{
try
{
qMgr.disconnect();
}
catch
(MQException e) {
e.printStackTrace();
return
message;
public
static
void
main(String args[]) {
sendMessage(
"this is a test by MQ API Binding model"
);