1

嗨开发者,

我想使用库名编写 2 个.java文件,分别是和.JMSMessageProducerMessageConsumer

我在我的文件夹中添加了activemq-all-5.8.0.jarcommons-io-2.4.jar文件。我lib将端口号Activemq从更改6161661617

使用MessageProducer.java文件,我会将消息发送到Activemq。为此,我编写了代码,它工作正常。如果您想查看,请单击此链接

在此处输入图像描述

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

收到MessageConsumer消息后,它将消息正文与消息分开,并仅在控制台上打印(仅用于我的测试)。为此,我编写了以下 2 个java文件。但它不起作用。

消息消费者.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);
}
};

我没有为 Queue in 配置目的地,Activemq console也没有在从MessageProducer.java.

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

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

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

任何人都可以建议我。

谢谢。

4

2 回答 2

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");

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


要阅读 a 的主体TextMessage,请使用类似这样的内容(引用自ActiveMQ hello world 示例

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                String text = textMessage.getText();
                System.out.println("Received: " + text);
            } else {
                System.out.println("Received: " + message);
            }
于 2013-08-08T15:31:50.380 回答
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。
于 2013-08-14T05:52:26.780 回答