【发布时间】:2015-10-18 14:10:25
【问题描述】:
我很高兴改进我在 Apache Tomcat 上运行的 Web 应用程序。添加了一个ActiveMQ JMS 服务器来发送和接收消息。
我已经可以发送和接收消息,但需要接收方的帮助。
我的网络应用应该如何持续监听一个队列来接收消息?
新消息到达,服务器应该对它们采取行动。例如:将数据添加到数据库或发送回消息。
我已经可以发送消息了。这是代码。
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = factory.createConnection();
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("clientQueue");
MessageProducer publisher = session.createProducer(queue);
connection.start();
Message message = null;
message = session.createTextMessage("Text Message");
publisher.send(message);
我已经可以在请求后收到一条消息(点击;-))
connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("serverQueue");
consumer = session.createConsumer(destination);
while (true) {
Message message = consumer.receive(300000);
//Do message stuff
}
我应该如何让 web 应用不断地监听队列? 建议的方式是什么?
热烈感谢所有帮助。谢谢。
编辑 - 解决方案
来自DaveH的建议的当前工作解决方案
我添加了一个 ServletContextListener 来持续收听我的消息。
web.xml
<listener>
<listener-class>com.test.JMSContextListener</listener-class>
</listener>
听众:
public class JMSContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent arg0) {
Thread thread = new Thread(new JMSConnector());
thread.start();
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//Nothing
}
}
连接:
public class JMSConnector implements Runnable {
public void run() {
try {
Context context = new InitialContext();
QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup("java:comp/env/jms/ConnectionFactory");
Connection connection = factory.createConnection();
Queue queue = (javax.jms.Queue) context.lookup("java:comp/env/jms/serverQueue");
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
//This MessageListener will do stuff with the message
MessageListenerImpl messageListener = new MessageListenerImpl();
consumer.setMessageListener(messageListener);
connection.start();
// Start connection or nothing will happen!!!
connection.start();
} catch (JMSException ex) {
//TODO
} catch (NamingException ex) {
//TODO
}
}
}
这是一个建议的方式还是应该改进?
热烈感谢所有帮助。谢谢。
【问题讨论】:
-
仅供参考:我没有使用 Spring...
-
对于Servlet容器3.x,可以用@WebListener注解监听器,无需在web.xml中声明。 (Mkyong)
标签: java tomcat queue jms activemq