无法使用activemq获取异步消息

时间:2012-09-28 08:23:51

标签: java activemq

大家好我无法使用活动mq接收异步消息,下面是我用于发布消息的代码并订阅它。

    public class publishMessage extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       InitialContext initCtx = new InitialContext();
            Context envContext = (Context) initCtx.lookup("java:comp/env");
            ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) envContext.lookup("jms/ConnectionFactory");
            Connection connection = connectionFactory.createConnection();
            connection.start() ;
            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue("jms/topic/MyQueue");
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT) ;
            TextMessage msg=session.createTextMessage();
            msg.setText("Message sent");
                    System.out.println("Message Sent");
            producer.send(msg);
            session.commit() ;
            connection.close() ;
            }catch(Exception ex){
                ex.printStackTrace() ;
            }
    }}


class Consumer{

    protected Queue queue;


    protected String queueName = "jms/topic/MyQueue";

    protected String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    protected int ackMode = Session.AUTO_ACKNOWLEDGE;

    public static void main(String[] args) {
        Consumer rec=new Consumer();
        try {
            rec.run();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void run() throws JMSException{

        System.out.println("URL:" + url);
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        TopicConnection connection = (TopicConnection)connectionFactory.createTopicConnection();
        connection.setClientID("Testingconn1") ;
        connection.start();
        MessageConsumer consumer = null;
        Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
        queue = session.createQueue(queueName) ;
        consumer = session.createConsumer(queue);
        consumer.setMessageListener(new MyListener()) ;
        session.commit() ;
        consumer.close();
        session.close();
        connection.close();
    }

}

package com.java;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class MyListener implements MessageListener{

    @Override
    public void onMessage( final Message message )
    {
        if ( message instanceof TextMessage )
        {
            final TextMessage textMessage = (TextMessage) message;
            try
            {
                System.out.println("Listener:" +  textMessage.getText() );
            }
            catch (final JMSException e)
            {
                e.printStackTrace();
            }
        }

    }
}

当我执行上面的代码时,发布者成功发送了一条消息,当我启动我的消费者时,输出就会根据需要出现,我的控制台没有输出。

帮助我解决它或建议接收异步消息的代码。

2 个答案:

答案 0 :(得分:1)

您的消费者代码实际上并没有让消费者随时消费该消息。当消费者将持续一段时间并且您的应用可以处理传入消息时,将使用异步消费者。在上面的代码中,您最好使用MessageConsumer中的定时接收方法,例如consumer.receive(5000)或某个适合您app的时间段。您不希望消费者在创建时立即收到消息,因为代理需要一段时间来注册消费者并将消息路由到消费者,因此您必须在应用中允许消费者。

答案 1 :(得分:1)

您的消费者类是正确的。它运行顺利。

但是,你的消费者是不正确的&你必须修改它。

  • 首先,在创建连接对象后添加setClientID(“any_string_value”);

     eg: Connection connection = connectionFactory.createConnection();
        // need to setClientID value, any string value you wish
        connection.setClientID("12345");
    
    • 其次,使用createDurableSubscriber()方法而不是createConsumer()来通过主题传输消息。

       MessageConsumer consumer = session.createDurableSubscriber(topic,"SUB1234");
      

以下是修改过的comsumer类:

package mq.test;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class consumer {
    // URL of the JMS server
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    // Name of the topic from which we will receive messages from = " testt"

    public static void main(String[] args) throws JMSException {
        // Getting JMS connection from the server

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();

        // need to setClientID value, any string value you wish
        connection.setClientID("12345");

        try{
        connection.start();
        }catch(Exception e){
            System.err.println("NOT CONNECTED!!!");
        }
        Session session = connection.createSession(false,
                Session.AUTO_ACKNOWLEDGE);

        Topic topic = session.createTopic("test_data");

        //need to use createDurableSubscriber() method instead of createConsumer() for topic
        // MessageConsumer consumer = session.createConsumer(topic);
        MessageConsumer consumer = session.createDurableSubscriber(topic,
                "SUB1234");

        MessageListener listner = new MessageListener() {
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println("Received message"
                                + textMessage.getText() + "'");
                    }
                } catch (JMSException e) {
                    System.out.println("Caught:" + e);
                    e.printStackTrace();
                }
            }
        };

        consumer.setMessageListener(listner);
        //connection.close();

    }
}