我正在使用 MQ v6 API 类编写一个简单的 Java 应用程序现在我可以在 while 循环中浏览远程队列。该程序作为 Windows 服务运行,必须中断然后服务停止。首先我设置 waitInterval=MQC.MQWI_UNLIMITED,但 MQMessage.get() 可以防止循环中断。然后我设置 waitInterval=5000 并捕获 MQRC_NO_MSG_AVAILABLE。这是一个正常的解决方案还是有更好的解决方案?
这是阅读周期的代码:
public class MessageConsumer {
private MessageListener ml;
private MQQueue queue;
private Thread sideThread;
static Logger logger = Logger.getLogger(MessageConsumer.class);
private static volatile boolean listening = true;
public MessageConsumer(MQQueue queue) {
this.queue = queue;
}
public void setMessageListener(MessageListener ml) throws MQException {
this.ml = ml;
start();
}
public synchronized void stop() {
this.listening = false;
logger.log(Priority.INFO, "listening = false");
sideThread.interrupt();
logger.log(Priority.INFO, "set sideThread.interrupt()");
}
private void listen() throws MQException {
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQC.MQGMO_WAIT + MQC.MQGMO_FAIL_IF_QUIESCING + MQC.MQGMO_LOGICAL_ORDER + MQC.MQGMO_ALL_SEGMENTS_AVAILABLE + MQC.MQGMO_COMPLETE_MSG + MQC.MQGMO_SYNCPOINT;
getOptions.waitInterval = 5000;//MQC.MQWI_UNLIMITED;
logger.log(Priority.INFO, "Start of listening");
int i = 1;
while (listening) {
// try {
System.out.println("Read message");
MQMessage message = new MQMessage();
logger.log(Priority.INFO, "Waiting message: ");
try {
queue.get(message, getOptions);
logger.log(Priority.INFO, "Get message: ");
if (ml != null) {
ml.onMessage(message);
}
} catch (MQException e) {
if (e.reasonCode == e.MQRC_NO_MSG_AVAILABLE) {
System.out.println("no more message available or retrived");
} else {
throw e;
}
}
}
logger.log(Priority.INFO, "End of listening");
}
private void start() throws MQException {
sideThread = new Thread(new Runnable() {
@Override
public void run() {
try {
listen();
} catch (MQException mqex) {
logger.log(Priority.ERROR, "A WebSphere MQ Error occured : Completion Code "
+ mqex.completionCode + " Reason Code "
+ mqex.reasonCode, mqex);
mqex.printStackTrace();
}
}
});
sideThread.start();
try {
sideThread.join();
} catch (InterruptedException ex) {
logger.log(Priority.INFO, "MessageConsumer.start()", ex);
java.util.logging.Logger.getLogger(MessageConsumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
};