Reprinted from: http://www.cnblogs.com/chenpi/p/5565618.html
read table of contents
foreword
I wrote a simple JMS example. The reason for using JNDI is for generality. This example uses the general interface provided by the JMS specification and does not use the interface of a specific JMS provider, so that the program we write can be guaranteed to be applicable to any kind of JMS implementation (ActiveMQ, HornetQ...).
What is JNDI
JNDI (Java Naming and Directory Interface) is a standard specification, similar to JDBC, JMS and other specifications, which provides developers with a common and unified interface for finding and accessing various naming and directory services. The J2EE specification requires that all J2EE containers provide an implementation of the JNDI specification, so Tomcat implements the JNDI specification.
Configuring JNDI with Tomcat
Find the conf folder under 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 to the bin directory under the ActiveMQ installation path, enter the "activemq start" command to start, and enter the address http://localhost:8161/admin in the browser to view information such as queues and topics.
Write a web project
Create a new web project on eclipse, add the jar package that ActiveMQ depends on, and then start to write two servlets, one for producing messages and the other for consuming messages, as follows:
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; importjavax.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 } }
消息消费者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 } }
验证结果
Run the web project in Tomcat, execute the message producer servlet, and return the message sending success sign. At the same time, we can view the message at http://localhost:8161/admin/queues.jsp , as shown in the following figure
Continue to execute the message consumer servlet and return the message reception success sign. At the same time, we can open the http://localhost:8161/admin/queues.jsp page and find that the message just now has disappeared, as shown in the following figure
References
http://howtodoinjava.com/jms/jms-point-to-point-message-example/