I am using IBM MQ as my queue service.
How to count the number of message in IBM MQ?
How-to
Here has the sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | package com.xxx.mql.service; import java.io.IOException; import java.util.Enumeration; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueBrowser; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.commons.lang.StringUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.base.Strings; import com.ibm.mq.jms.MQQueueConnection; import com.ibm.mq.jms.MQQueueConnectionFactory; import com.ibm.mq.jms.MQQueueReceiver; import com.ibm.mq.jms.MQQueueSession; import com.tdcc.common.type.MQInfoEnum; import com.tdcc.mql.utils.MqlUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class TestMQService { private static TestMQService mqServuce; private static String mqHost = MQInfoEnum.MQ_HOST.getValue(); private static String mqChannel = MQInfoEnum.MQ_CHANNEL.getValue(); private static String mqUser = MQInfoEnum.MQ_USER.getValue(); private static String mqPwd = ""; private static String mqQueueMgr = MQInfoEnum.MQ_QUEUEMGR.getValue(); public static TestMQService getInstance() { if (mqServuce == null) { mqServuce = new TestMQService(); return mqServuce; } else { return mqServuce; } } /** * 透過 JMS 去查詢 queue 裡面有幾筆訊息. * * @param queueName * @return * @throws JMSException */ public int getNumOfMsg(String queueName) throws JMSException { MQQueueConnectionFactory connFactory = new MQQueueConnectionFactory(); MQQueueReceiver receiver = null; MQQueueSession session = null; MQQueueConnection connection = null; int numOfMsg = 0; try { // Config connFactory.setHostName(mqHost); connFactory.setPort(1414); connFactory.setTransportType(1); connFactory.setQueueManager(mqQueueMgr); connFactory.setChannel(mqChannel); connection = (MQQueueConnection) connFactory.createQueueConnection(); session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); receiver = (MQQueueReceiver) session.createReceiver(queue); connection.start(); QueueBrowser queueBrowser = session.createBrowser((Queue) queue); Enumeration msgEnum = queueBrowser.getEnumeration(); while (msgEnum.hasMoreElements()) { Message message = (Message) msgEnum.nextElement(); numOfMsg++; } } catch (JMSException e) { log.error(MqlUtils.toStackTrace(e)); } finally { if (receiver != null) { receiver.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } log.info("[getNumOfMsgByJMS] numOfMsg = " + numOfMsg); return numOfMsg; } } |