Implement point-to-point message transmission of JMS Based on Tomcat + JNDI + ActiveMQ

Source: Internet
Author: User

Implement point-to-point message transmission of JMS Based on Tomcat + JNDI + ActiveMQ

I wrote a simple JMS example. The reason for using JNDI is for universality. This example uses the common interface provided by the JMS specification and does not use the interface of a specific JMS provider, this ensures that the program we write applies to any JMS implementation (ActiveMQ, HornetQ ...).

What is JNDI

Java Naming and Directory Interface is a standard specification similar to JDBC, JMS, and other specifications. It provides developers with universal and unified interfaces for searching and accessing various Naming and Directory services. The J2EE specification requires that all J2EE containers provide the implementation of the jndi specification, so Tomcat implements the JNDI specification.

Use Tomcat to configure JNDI

Find the conf folder in the Tomcat installation path, open context. xml, and add the following Configuration:

 <Resource name="queue/connectionFactory"                    auth="Container"                    type="org.apache.activemq.ActiveMQConnectionFactory"                  description="JMS Connection Factory"                  factory="org.apache.activemq.jndi.JNDIReferenceFactory"                  brokerURL="tcp://localhost:61616"                  brokerName="LocalActiveMQBroker" />                    <Resource name="queue/queue0"                    auth="Container"                    type="org.apache.activemq.command.ActiveMQQueue"                  description="My Queue"                  factory="org.apache.activemq.jndi.JNDIReferenceFactory"                  physicalName="TomcatQueue" /> 
Start ActiveMQ

CMD: Go to the bin directory in the ActiveMQ installation path and enter the "activemq start" command to start the service. You can enter the address http: // localhost: 8161/admin in the browser, view queue, topic, and other information.

Compile a Web Project

Create a web project on eclipse, add the jar package that ActiveMQ depends on, and then write two Servlets, one for message production and the other for message consumption. The following code:

Message producer Servlet:

import java.io.IOException;import java.io.PrintWriter;import javax.jms.DeliveryMode;import javax.jms.Queue;import javax.jms.QueueConnection;import javax.jms.QueueConnectionFactory;import javax.jms.QueueSender;import javax.jms.QueueSession;import javax.jms.Session;import javax.jms.TextMessage;import javax.naming.InitialContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class JMSTest */@WebServlet("/Send")public class Send extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public Send() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        PrintWriter out = response.getWriter();        try {            // get the initial context            InitialContext context = new InitialContext();            // lookup the queue object            Queue queue = (Queue) context.lookup("java:comp/env/queue/queue0");            // lookup the queue connection factory            QueueConnectionFactory conFactory = (QueueConnectionFactory) context                    .lookup("java:comp/env/queue/connectionFactory");            // create a queue connection            QueueConnection queConn = conFactory.createQueueConnection();            // create a queue session            QueueSession queSession = queConn.createQueueSession(false,                    Session.DUPS_OK_ACKNOWLEDGE);            // create a queue sender            QueueSender queSender = queSession.createSender(queue);            queSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);            // create a simple message to say "Hello World"            TextMessage message = queSession.createTextMessage("Hello World");            // send the message            queSender.send(message);            // print what we did            out.write("Message Sent: " + message.getText());            // close the queue connection            queConn.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }}

Message consumer Servlet:

import java.io.IOException;import java.io.PrintWriter;import javax.jms.Queue;import javax.jms.QueueConnection;import javax.jms.QueueConnectionFactory;import javax.jms.QueueReceiver;import javax.jms.QueueSession;import javax.jms.Session;import javax.jms.TextMessage;import javax.naming.InitialContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class Receive */@WebServlet("/Receive")public class Receive extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public Receive() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        PrintWriter out = response.getWriter();        try {            // get the initial context            InitialContext context = new InitialContext();            // lookup the queue object            Queue queue = (Queue) context.lookup("java:comp/env/queue/queue0");            // lookup the queue connection factory            QueueConnectionFactory conFactory = (QueueConnectionFactory) context                    .lookup("java:comp/env/queue/connectionFactory");            // create a queue connection            QueueConnection queConn = conFactory.createQueueConnection();            // create a queue session            QueueSession queSession = queConn.createQueueSession(false,                    Session.AUTO_ACKNOWLEDGE);            // create a queue receiver            QueueReceiver queReceiver = queSession.createReceiver(queue);            // start the connection            queConn.start();            // receive a message            TextMessage message = (TextMessage) queReceiver.receive();            // print the message            out.write("Message Received: " + message.getText());            // close the queue connection            queConn.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }}
Verification Result

Run the Web Project in Tomcat, execute the message producer Servlet, and return the message sending success flag. At the same time, we can go to http: // localhost: 8161/admin/queues. view the message in jsp, as shown in

Continue to execute the message consumer Servlet and return the message receipt success mark. At the same time, we can enable http: // localhost: 8161/admin/queues. on the jsp page, the message is missing, as shown in

 

Code reference: http://howtodoinjava.com/jms/jms-point-to-point-message-example/

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.