1. 程式人生 > >配置監聽器使項目啟動時創建消費者

配置監聽器使項目啟動時創建消費者

static web 項目 throw 監聽 註意 eve tap factory

1、web.xml中註冊監聽器
<listener>
<listener-class>com.activemq.common.InitComponent</listener-class>
</listener>
2、InitComponent實現ServletContextListener,ApplicationContextAware接口,重寫contextInitialized(ServletContextEvent servletContextEvent)方法。

特別註意,如果使用spring管理activemq,要修改配置與實際生產一致。這種方式會在項目啟動時創建消費者,若項目做了負載均衡,多個Tomcat啟動項目,會造成有多個消費者客戶端。

@Component
public class InitComponent implements ServletContextListener,ApplicationContextAware{

private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
InitComponent.applicationContext=applicationContext;
}
/**
* 程序運行時即初始化activemq消費組件
*/
public void contextInitialized(ServletContextEvent servletContextEvent) {

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://132.252.3.22:61616");
Connection connection;
Session session;
Destination destination;
MessageConsumer messageConsumer;
try {
connection = factory.createConnection();
connection.start();
session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic("ZHXJ_QUEUE"); // 創建連接的消息隊列
messageConsumer = session.createConsumer(destination);// 創建消息消費者
messageConsumer.setMessageListener(new StaffMsgListener());
} catch (JMSException e) {
e.printStackTrace();
}
}
}

配置監聽器使項目啟動時創建消費者