如何通过apacheMQ在两个servlet之间发送消息?

时间:2015-05-02 08:21:29

标签: java tomcat servlets web-applications activemq

我正在尝试将apacheMQ集成到我在Tomcat上运行的Web应用程序中。我找到了一些关于本地集成的教程(我不打算进行全局集成),但我不知道如何继续。所有的教程似乎都让初学者感到困惑。

请您查看我的代码并建议我是否正确地实施此代码?我的目的是从一个servlet发送一些消息(将其添加到队列中),然后从具有不同servlet的队列中读取这些消息。

此代码基于THIS TUTORIAL

处理消息的类:

public class Messenger {

    public static void sendMessage(String msg) {
        // configure the broker
        try {
            // Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                    "vm://localhost");

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();

            // Create a Session
            Session session = connection.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue("TEST.FOO");

            // Create a MessageProducer from the Session to the Topic or Queue
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            // Create a messages
            TextMessage message = session.createTextMessage(msg);

            // Tell the producer to send the message
            System.out.println("Sent message: " + message.getText());
            producer.send(message);

            // Clean up
            session.close();
            connection.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void readQueue() {
        try {

            // Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                    "vm://localhost");

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();

            // Create a Session
            Session session = connection.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue("TEST.FOO");

            // Create a MessageConsumer from the Session to the Topic or Queue
            MessageConsumer consumer = session.createConsumer(destination);

            // Wait for a message
            Message message = consumer.receive(1000);

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

            consumer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            System.out.println("Caught: " + e);
            e.printStackTrace();
        }
    }

}

目前,我可以在控制台中打印所有内容,因为此示例仅用于测试和调试目的。

发送和接收servlet:

public class SendMessageServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        Messenger.sendMessage("Test message");


    }

}

public class ReadQueueServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        Messenger.readQueue();

    }

}

访问ReadQueueServlet的结果只是“Received:null”。

我不确定是否应该在此方案中为我的Web应用程序创建context.xml,但我也尝试过。我将以下内容放在WEB-INF/META-INF/context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource auth="Container"
          name="jms/ConnectionFactory"
          type="org.apache.activemq.ActiveMQConnectionFactory"
          description="JMS Connection Factory"
          factory="org.apache.activemq.jndi.JNDIReferenceFactory"
          brokerURL="vm://localhost?brokerConfig=xbean:activemq.xml"
          brokerName="MyActiveMQBroker"/>

<Resource auth="Container"
          name="jms/FooQueue"
          type="org.apache.activemq.command.ActiveMQQueue"
          description="JMS queue"
          factory="org.apache.activemq.jndi.JNDIReferenceFactory"
          physicalName="FOO.QUEUE"/>
</Context>

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

  

访问ReadQueueServlet的结果只是“Received:null”。

这是因为队列中没有消息。

        // Wait for a message
        Message message = consumer.receive(1000);

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

如果您看到接收方法的documentation

  

返回:       为此消息使用者生成的下一条消息,如果超时过期或此消息使用者同时关闭,则为null

所以在时间到期后你会得到null。您的代码进入else块并打印无效的消息。