首页 > 解决方案 > Spring JMS - MessageListener 类中消息的延迟处理

问题描述

我的应用程序在 WAS 8.5 上运行并使用 JMS MessageListener 使用来自 IBM MQ 9 的消息。当我的应用程序最初启动时,还会通过访问数据库中的数据形成缓存。但是,如果 JVM 的任何重新启动或停止/启动完成,我的应用程序将进入空指针状态,因为缓存未完全加载并且 onMessage 方法开始从 MQ 获取消息。Spring 使用缓存进行依赖注入。在这种情况下,我该如何停止或 MessageListener 类如何等待缓存完全加载。下面是我的 MessageListener 以及 LoadCache 类的代码片段。

JMS 消息监听器

public class MQMessageConsumer implements MessageListener {
    private static Log log = LogFactory.getLog(MQMessageConsumer.class);

    ExecutorService executor = Executors.newFixedThreadPool(500);

    @SuppressWarnings("unchecked")
    public void onMessage(Message message) {
        log.debug("There is a message in the Queue");
        String inputXML = null;

        if (message instanceof TextMessage) {
            try {
                inputXML = ((TextMessage) message).getText();

                MQMessageProcessor mqp = new MQMessageProcessor(inputXML);
                executor.submit(mqp);
            } catch (Exception e) {
                log.error("Error in processing the message - " + e.getMessage());
            }
        } else
            log.error("Invalid message format, please resend with correct MQ message header as MQSTR");

    }
}

加载缓存

public class LoadCache implements ServletContextListener{

    private Cache cache;
    protected static Log log = LogFactory.getLog(LoadCache.class);
    private ApplicationService service = new ApplicationService();

    public void contextInitialized(ServletContextEvent event){
        cache = Cache.getCache();
        try {
            System.out.println("Cache building started during strtup");
            /*log.debug("Cahe building started during strtup");*/
            long startTime = System.currentTimeMillis();
            loadProperties(cache);
            loadDataTable(cache);
            loadOP(cache);
            loadUCM(cache);
            long endTime = System.currentTimeMillis() ;
            System.out.println("Total Cache building time is :"+(endTime - startTime));
            /*log.debug("Total Cache building time is :"+(endTime - startTime));*/
        } catch (DataAccessException e) {
            e.printStackTrace();
            log.debug("Error While communicating to database:"+e.getMessage());
        }
    }

    public void contextDestroyed(ServletContextEvent event){
        System.out.println("Context Destroyed-LoadCache Gone");
    }

}

如何让我的应用程序侦听器等到缓存加载?我还尝试在 MessageConsumer 类中创建一个默认构造函数并添加了 20 秒的线程睡眠,但这也没有帮助。关于如何实现这一点的任何修复?

标签: springjmsibm-mqspring-jmswebsphere-8

解决方案


推荐阅读