找到你要的答案

Q:How to Send message via apacheMQ in between two servlets?

Q:如何通过apachemq之间servlet发送消息?

I am trying to integrate apacheMQ in my web application running on Tomcat. I found some tutorials about local integration (I do not intend to do the global integration) but I am not sure how to proceed. All the tutorials seem to be quite confusing to a beginner.

Could you please take a look on my code and suggest if I am on a right path to implement this? My intention is to send some messages from one servlet (add it to queue) and then read these message from a queue with different servlet.

This code is based on THIS TUTORIAL.

Class for handling messages:

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();
        }
    }

}

At the moment, it is enough for me to print everything in console since this example is only for testing and debugging purposes.

Sending and receiving servlets:

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

    }

}

The result of accessing the ReadQueueServlet is just "Received: null".

I am not sure if I should create a context.xml for my web application in this scenario but I tried that as well. I placed the following in 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>

Any help is appreciated.

我想把我apachemq Web应用运行在Tomcat。我找到了一些关于本地集成的教程(我不打算做全局集成),但我不知道如何进行。所有的教程似乎是相当困惑的初学者。

请你看看我的代码,并建议如果我在一个正确的路径来实现这一点?我打算从一个servlet发送一些信息(添加到队列),然后读取这些信息从不同的Servlet队列。

本代码基于本教程。

处理消息的类:

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();
        }
    }

}

目前,这是足以让我打印一切在控制台,因为这个例子只用于测试和调试的目的。

发送和接收程序:

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结果只是“接收的空”。

我不知道我是否应该创建一个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>

任何帮助是赞赏。

answer1: 回答1:

The result of accessing the ReadQueueServlet is just "Received: null".

This is because there no message in the queue.

        // 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);
        }

If you see documentation of receive method

Returns: the next message produced for this message consumer, or null if the timeout expires or this message consumer is concurrently closed

So after time expires you get null. Your code enters else block and prints message which is null.

访问readqueueservlet结果只是“接收的空”。

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

        // 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);
        }

如果你看到接收方法的文档

Returns: the next message produced for this message consumer, or null if the timeout expires or this message consumer is concurrently closed

所以时间到期后你得到空。您的代码进入其他块并打印消息,这是空的。

java  tomcat  servlets  web-applications  activemq