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();
}
}
}
原文地址:https://www.cnblogs.com/xyhero/p/9404595.html