【问题标题】:Count number of messages in a JMS queue计算 JMS 队列中的消息数
【发布时间】:2012-11-16 05:42:28
【问题描述】:

遍历 JMS 队列并获取其中所有消息的最佳方法是什么?

如何计算队列中的消息数?

谢谢。

【问题讨论】:

标签: java jms activemq message-queue


【解决方案1】:

Java 8 和 Spring Boot

   public int countPendingMessages(String destination) {
    // to an Integer because the response of .browse may be null
    Integer totalPendingMessages = this.jmsTemplate.browse(destination, (session, browser) -> Collections.list(browser.getEnumeration()).size());

    return totalPendingMessages == null ? 0 : totalPendingMessages;
   }

【讨论】:

    【解决方案2】:

    使用 JmsTemplate

    public int getMessageCount(String messageSelector)
    {
        return jmsTemplate.browseSelected(messageSelector, new BrowserCallback<Integer>() {
            @Override
            public Integer doInJms(Session s, QueueBrowser qb) throws JMSException
            {
                return Collections.list(qb.getEnumeration()).size();
            }
        });
    }
    

    【讨论】:

    • 为了完整起见:这是给 Spring 框架的用户的。
    • 我发现了一个问题,队列大小有时会返回 0,对于我们的用例来说,这会导致工作失败,不知道为什么,但是其他人在使用它时是否遇到了可靠性问题?跨度>
    • 我可以从 jmstemplate 获取出队的 msg 计数吗?
    【解决方案3】:

    这是计算队列中消息数的方法

    public static void main(String[] args) throws Exception
        {
            // get the initial context
            InitialContext ctx = new InitialContext();
    
            // lookup the queue object
            Queue queue = (Queue) ctx.lookup("queue/queue0");
    
            // lookup the queue connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
                lookup("queue/connectionFactory");
    
            // create a queue connection
            QueueConnection queueConn = connFactory.createQueueConnection();
    
            // create a queue session
            QueueSession queueSession = queueConn.createQueueSession(false,
                Session.AUTO_ACKNOWLEDGE);
    
            // create a queue browser
            QueueBrowser queueBrowser = queueSession.createBrowser(queue);
    
            // start the connection
            queueConn.start();
    
            // browse the messages
            Enumeration e = queueBrowser.getEnumeration();
            int numMsgs = 0;
    
            // count number of messages
            while (e.hasMoreElements()) {
                Message message = (Message) e.nextElement();
                numMsgs++;
            }
    
            System.out.println(queue + " has " + numMsgs + " messages");
    
            // close the queue connection
            queueConn.close();
        }
    

    【讨论】:

    • 我实际上运行了这个示例,由于某种原因,当我在队列中有 5000 条消息时,消息计数显示为 400
    • 怎么说你有 5000 条消息在一个队列中。
    • 我在我的 ActiveMQ 控制台上实际看到它
    • 您在单次执行或多次发送它,如果多次尝试 ActiveMQ 在您检查时是否正在运行。
    • 我的接收者收到的消息数量随着消息数量的增加而得到
    猜你喜欢
    • 2010-09-19
    • 1970-01-01
    • 2012-01-19
    • 2019-07-15
    • 2011-10-01
    • 2013-03-10
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多