当 Queue 中的消息为零时,确定何时终止 SpringBoot 中的 Jms Listener

Determining when to terminate a Jms Listener in SpringBoot when Queue has zero messages

决定何时杀死听众的正确方法或流行惯例是什么?我似乎无法在任何地方找到可靠的答案。我正在处理的队列是 IBM 的 MQ 队列,我知道您通常会阅读直到收到 2033 错误代码(我公司在其他应用程序中这样做),此时您可以结束,但对于 SpringBoot Jms 应用程序这里的约定是什么?一旦队列为空,监听器就会挂起,直到有更多消息到来。如果我想,我知道如何杀死它,但我怎么知道什么时候?

例如,这是我拼凑的示例项目的配置

@Configuration
@EnableTransactionManagement
public class JmsConfig {

@Bean
protected DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory() throws JMSException {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
    factory.setConnectionFactory(mqQueueConnectionFactory());
    factory.setConcurrency("1");
    factory.setSessionTransacted(true);
    factory.setAutoStartup(true);
    factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
        factory.setErrorHandler(new JmsErrorHandler());
    return factory;
}

@Bean
public MQQueueConnectionFactory mqQueueConnectionFactory() {
    MQQueueConnectionFactory mqQueueConnectionFactory = new MQQueueConnectionFactory();
    mqQueueConnectionFactory.setHostName(host);
    try {
        mqQueueConnectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
        mqQueueConnectionFactory.setCCSID(1208);
        mqQueueConnectionFactory.setChannel(channel);
        mqQueueConnectionFactory.setPort(port);
        mqQueueConnectionFactory.setQueueManager(queueManager);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mqQueueConnectionFactory;
}

这里是监听器

@Component
public class Consumer {

    @JmsListener(id = "myQueue", destination = "queue")
    public void processMessage(Message message) throws MQException, IOException {
        try {
            String messageString = ((TextMessage) message).getText();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

除了主要的 class 和 ErrorHandler,这就是整个示例项目,它将处理消息。我在其他应用程序中所做的是在给定队列值的情况下实例化一个 MQQueue 并简单地执行 queue.getCurrentDepth() 如果我得到一个零,我然后调用一个 ListenerContainerController 的实例,然后从 JmsListenerEndpointRegistry 调用停止给定队列 ID。

Spring 是否有简单的沟通方式 "hey your queue is now empty" 或者有没有办法在 x 时间过去后结束它?

A JmsListener 用于在消息到达目的地时接收和处理消息。它不打算读到目的地为空然后停止,它旨在保持 运行。

而是使用 JmsTemplate 及其 receive 方法来读取消息,直到它们完成。然后处理它们并写一份报告。

最终您甚至可以使用 JmsItemReader 创建一个 Spring 批处理作业,此 reader 将一直读取,直到没有更多内容可读取,然后全部结束。在它下面还使用了一个 JmsTemplate

然后您可以做的是,当您使用 Spring 启动时,使用 cron 作业每天触发此作业(这基本上完成启动您创建的 jar)。另请参阅 Spring Boot 的参考指南,了解如何使用 batch applications