I am happily improving my web application that runs on Apache Tomcat . To send and receive messages, the JMS ActiveMQ server has been added.
I can already send and receive messages, but you need help on the recipient side.
How will my web application constantly listen to one queue for receiving messages?
New messages arrive, and the server must act on them. Example: adding data to the database or sending a message back.
I can already send messages. This is the code.
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);
I can already receive the message after the request (click ;-))
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);
How can I let a web application listen to the queue continuously? What is the recommended way?
All help is appreciated. Thanks.
EDITING - SOLUTION
Current working solution with DaveH offers
I added a ServletContextListener to listen to my message continuously.
web.xml
<listener> <listener-class>com.test.JMSContextListener</listener-class> </listener>
Listeren:
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) {
Compound:
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);
Is this the recommended way or should it be improved?
All help is appreciated. Thanks.