简体   繁体   中英

ActiveMQ, how can i create only one consumer?

I'm working with Java EE and ActiveMQ. I want to realize a JMS Queue where I can send messages to my QUEUE and a Consumer + MessageListener should read this messages.

The Code for my Consumer ist the following:

private void initializeActiveMq() throws JMSException {
            // Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
            // Create a Connection
             connection = connectionFactory.createConnection();
             connection.start();
            // Create a Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);


            // Create the destination (Queue)
            Queue queue = session.createQueue(queueName);
             // Create a MessageConsumer from the Session to the Queue
             consumer = session.createConsumer(queue);

             consumer.setMessageListener(this);

    }

But the problem is, every time i will run this code it ads a new consumer to my queue, and then i have some strange behavior the consumers did then not deliver the messages correctly. If i have only one consumer it works perfect.

So how can I make sure that I have only one consumer in my queue?

I've experienced the exact same issue. You need to make sure that your war has a concept of a graceful shutdown procedure when undeployed.

You can achieve this by having a HTTP Servlet that implements init (do all your initialisation here) and destroy (do all you clearing down here). Destory() will get get called by the JVM when the war is undeployed.

I use Spring to define all my beans, ActiveMQ connections, message consumers and producers. My init() loads the Spring application context from a master xml file, caches a reference to it locally, then the destory() calls close() on the application context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM