如何将消息从Activemq推送到Java应用程序

时间:2013-08-08 14:02:55

标签: java jms activemq java-ee-6

嗨开发者,

我想使用.java库名JMSMessageProducer来编写2 MessageConsumer个文件。

我在activemq-all-5.8.0.jar文件夹中添加了commons-io-2.4.jarlib个文件。我将Activemq的端口号从61616更改为61617

使用MessageProducer.java文件,我会向Activemq发送消息。为此,我编写的代码工作正常。如果您想点击此Link

enter image description here

我想从ActivemqMessageConsumer.java发送消息。这是应用程序位于Apache Tomcathttp://localhost:8080/ExecutableFileProcess/MessageConsumer

一旦MessageConsumer收到消息,它就会将消息体与消息分开,它只是在控制台上打印(仅供我测试)。为此,我编写了以下2个java文件。但它是不工作。

MessageConsumer.java:

 package PackageName;
 import java.io.IOException;
 import javax.jms.Connection;
 import javax.jms.ConnectionFactory;
 import javax.jms.MessageListener;
 import javax.jms.Queue;
 import javax.jms.Session;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.activemq.ActiveMQConnectionFactory;
 public class MessageConsumer extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
        throws ServletException, IOException {
try {
    //creating connectionfactory object for way
    ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin","admin","tcp://localhost:61617");
    //establishing the connection b/w this Application and Activemq
    Connection connection=connectionFactory.createConnection();
    Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue=session.createQueue("MessageTesing");
    javax.jms.MessageConsumer consumer=session.createConsumer(queue);
    //fetching queues from Activemq
    MessageListener listener = new MyListener();
    consumer.setMessageListener(listener);
    connection.start();
} catch (Exception e) {
    // TODO: handle exception
}

}
}

MyListener.java:

package PackageName;
import javax.jms.Message;
import javax.jms.MessageListener;
public class MyListener implements MessageListener {
public void onMessage(Message msg) {
    System.out.println(msg);
}
};

我没有在Activemq console中为队列配置目的地,也没有在从MessageProducer.java发送消息时提及“目的地”。

我正在使用Eclipse。如何在控制台中打印messagebody,实际上基于messagebody我将在MessageConsumer.java中执行一些操作。但是对于我的测试,我需要看到messagebody。

我希望,你明白我在尝试什么。

我是JMSJava的新手,所以你能解释清楚。到目前为止,我使用谷歌搜索编写了代码。但我没有找到任何问题。

任何人都可以建议我。

感谢。

2 个答案:

答案 0 :(得分:1)

您的程序可能只是启动和终止,因为您编写了客户端以异步方式接收消息(使用MessageListener,在不同的线程中),并且您的主线程刚刚终止

尝试这样的事情:

                connection.start();

                System.out.println("Press a key to terminate");
                try {
                    System.in.read();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                System.out.println("End");

这应该让你的程序保持运行,直到你按下一个键。


要阅读TextMessage的正文,请使用以下内容(引自ActiveMQ hello world examples

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                String text = textMessage.getText();
                System.out.println("Received: " + text);
            } else {
                System.out.println("Received: " + message);
            }

答案 1 :(得分:1)

import java.io.Serializable;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

public class ActiveMQConnection {

    private static final long timeout = 3000L;

    private Logger logger = Logger.getLogger(ActiveMQConnection.class);

    private String activeMQUser; 
    private String activeMQPassword;
    private String activeMQURI;
    private String activeMQQueueName;

    private ActiveMQConnectionFactory connectionFactory;
    private Connection connection;
    private Session session;
    private boolean isConnected;

    private boolean transacted = false;
    private Destination destinationQueue;


    private boolean isQueueAvailable;
    private boolean isProducerAvailable;
    private boolean isConsumerAvailable;

    private MessageProducer producerForQueue;
    private MessageConsumer consumerForQueue;

    /**
     * Create Default service
     * @throws Exception 
     */
    public ActiveMQConnection() throws Exception
    {
        try {
                throw new JMSException("No Parameters defined for creating connection. Try constructor with parameters.");
        } catch (JMSException e) {
            logger.error("JMS Exception in Active MQ Connection",e);
            throw e;
        } catch (Exception e) {
            logger.error("JMS Exception in Active MQ Connection",e);
            throw e;
        }
    }


    /**
     * Create a service with desired parameters.
     * @param activeMQUser
     * @param activeMQPassword
     * @param activeMQURI
     * @param activeMQQueueName
     * @throws Exception 
     */
    public ActiveMQConnection(String activeMQUser, String activeMQPassword, String activeMQURI) throws Exception
    {
        try {
            this.activeMQUser = activeMQUser;
            this.activeMQPassword = activeMQPassword;
            this.activeMQURI =  activeMQURI;
            setUpActiveMQConnection();

        } catch (JMSException e) {
            logger.error("JMS Exception in Active MQ Connection",e);
            throw e;
        } catch (Exception e) {
            logger.error("Exception in Active MQ Connection",e);
            throw e;
        }
    }

    /**
     * @throws JMSException, Exception 
     */
    private void setUpActiveMQConnection() throws JMSException, Exception
    {
        connectionFactory = new ActiveMQConnectionFactory(
                this.activeMQUser,
                this.activeMQPassword,
                this.activeMQURI );
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
            isConnected = true;
        }catch (JMSException e) {
            isConnected = false;
            throw e;
        }catch(Exception e){
            isConnected = false;
            throw e;
        }
    }

    /**
     * @throws Exception
     */
    public void setUpQueue(String queueName ) throws Exception
    {
        this.activeMQQueueName = queueName;
        createQueue();
        createProducer();
        createConsumer();
    }

    /**
     * @throws Exception
     */
    private void createQueue() throws Exception 
    {
        try {
            if(destinationQueue == null)
                {   
                destinationQueue = session.createQueue(this.activeMQQueueName);
                isQueueAvailable = true;
                }
        } catch (JMSException e) {
            isQueueAvailable = false;
            throw e;
        }catch(Exception e){
            isQueueAvailable = false;
            throw e;
        }
    }

    /**
     * @throws JMSException 
     * 
     */
    private void createProducer() throws JMSException
    {   
        if(producerForQueue == null)
        {   
            try {
                producerForQueue = session.createProducer(destinationQueue);
                producerForQueue.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                isProducerAvailable = true;
            } catch (JMSException e) {
                isProducerAvailable = false;
                throw e;
            }
        }
    }

    /**
     * @throws JMSException
     */
    private void createConsumer() throws JMSException
    {   
        if(consumerForQueue == null)
        {   
            try {
                consumerForQueue = session.createConsumer(destinationQueue);
                isConsumerAvailable = true;
            } catch (JMSException e) {
                isConsumerAvailable = false;
                throw e;
            }
        }
    }

    /**
     * @param objectToQueue
     * @throws JMSException
     */
    public void sendMessage(Serializable objectToQueue) throws JMSException 
    {
        ObjectMessage message = session.createObjectMessage();
        message.setObject(objectToQueue);
        producerForQueue.send(message);
    }

    /**
     * @param objectToQueue
     * @throws JMSException
     */
    public Serializable receiveMessage() throws JMSException 
    {
        Message message = consumerForQueue.receive(timeout);
        if (message instanceof ObjectMessage) 
              { 
                  ObjectMessage objMsg = (ObjectMessage) message;
                  Serializable sobject = objMsg.getObject();
                  return sobject;
              }
        return null;
    }

    /**
     * close-MQ-Connection
     */
    public void closeMQConnection()
    {
        try 
        {
            if(consumerForQueue != null)
            {
            consumerForQueue.close();
            }
            if(producerForQueue != null)
            {
            producerForQueue.close();
            }
            if(session != null)
            {
            session.close();
            }
            if(connection != null )
            {
            connection.close();
            }   
        } 
        catch (JMSException e) 
            {
            logger.info("Error while closing connection.",e);
            }
        finally
            {
            consumerForQueue = null;
            producerForQueue = null;
            destinationQueue = null;
            session = null;
            connection = null;
            activeMQUser = null;
            activeMQPassword = null;
            activeMQQueueName = null;
            activeMQURI = null;
            }
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void setConnected(boolean isConnected) {
        this.isConnected = isConnected;
    }

    public boolean isQueueAvailable() {
        return isQueueAvailable;
    }

    public void setQueueAvailable(boolean isQueueAvailable) {
        this.isQueueAvailable = isQueueAvailable;
    }

    public boolean isProducerAvailable() {
        return isProducerAvailable;
    }

    public void setProducerAvailable(boolean isProducerAvailable) {
        this.isProducerAvailable = isProducerAvailable;
    }

    public MessageConsumer getConsumerForQueue() {
        return consumerForQueue;
    }

    public void setConsumerForQueue(MessageConsumer consumerForQueue) {
        this.consumerForQueue = consumerForQueue;
    }

    public boolean isConsumerAvailable() {
        return isConsumerAvailable;
    }

    public void setConsumerAvailable(boolean isConsumerAvailable) {
        this.isConsumerAvailable = isConsumerAvailable;
    }
}

上面是

的实用工具类
  • creating connection creating/connecting to queue sending message receiving message
  • 您可以使用其中的方法发送或接收任何可序列化的POJO。