简体   繁体   中英

Consume messages on an ActiveMQ retro actively

I have used the following java application to put a message on a JMS queue

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {
public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");
    JmsMessageSender jmsMessageSender = (JmsMessageSender)ctx.getBean("jmsMessageSender");

    java.lang.String text = "{\"name\": \"Bob\"}";
    jmsMessageSender.send(text);
    ((ClassPathXmlApplicationContext)ctx).close();
}

}

The message sender looks like this:

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

@Service
public class JmsMessageSender {
@Autowired
private JmsTemplate jmsTemplate;
public void send(final String text) {
    this.jmsTemplate.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            Message message = session.createTextMessage(text);
            return message;
        }
    });
}


}

And the spring config is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:beans="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.intonilof" />
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <constructor-arg index="0" value="tcp://127.0.0.1:61616" />
</bean>

<bean id="connectionFactory"
      class="org.springframework.jms.connection.CachingConnectionFactory">
    <constructor-arg ref="amqConnectionFactory" />
</bean>

<bean id="defaultDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg index="0" value="emailsToSend" />
</bean>

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestination" ref="defaultDestination" />
</bean>

If I use this code to put the message on how can I create a consumer for the topic which will come and consume the jms message at a later time?

I have tried the following but it is not consuming the message:

import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import java.util.Date;

public class App {
final static Logger logger = Logger.getLogger(App.class);
public static void main(String[] args) throws Exception {
    thread(new HelloWorldConsumer(), false);
}

public static void thread(Runnable runnable, boolean daemon) {
    Thread brokerThread = new Thread(runnable);
    brokerThread.setDaemon(daemon);
    brokerThread.start();
}

public static class HelloWorldConsumer implements Runnable, ExceptionListener {

    public void run() {
        try {
            logger.trace("Running at: " + new Date().toString());
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
            Connection connection = connectionFactory.createConnection();
            connection.start();
            connection.setExceptionListener(this);
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("emailsToSend?consumer.retroactive=true");
            MessageConsumer consumer = session.createConsumer(topic);
            Message message = consumer.receive(1000);

            if (message instanceof TextMessage) {
                    System.out.println("Found message");

            } else if (message == null){
                logger.trace("No messages");
            }
            consumer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            logger.info("Caught: " + e);
            e.printStackTrace();
        }
    }

    public synchronized void onException(JMSException ex) {
        logger.trace("JMS Exception occured.  Shutting down client.");
    }
}
}

You need to create durable topic subscription first. Then JMS will retain all published messages while the subscriber is disconnected and deliver them when it reconnects.

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