Writing a simple JMS example, the use of Jndi is for versatility, and the example uses the generic interface provided by the JMS specification, without using the interface of the specific JMS provider, which guarantees that the program we write is suitable for any JMS implementation (ActiveMQ, HornetQ ...).
What is Jndi
JNDI (Java naming and directory Interface) is a standard specification, similar to a specification such as JDBC,JMS, that provides developers with a common, unified interface for locating and accessing various naming and directory services. The Java EE specification requires that all the Java EE containers provide implementations of the JNDI specification, so Tomcat implements the JNDI specification.
Configuring Jndi with Tomcat
Locate the Conf folder under the Tomcat installation path, open context.xml, and add the following configuration:
<Resourcename= "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" /> <Resourcename= "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, you can enter the address http://localhost:8161/admin in the browser, view queues, topics and other information.
Write a Web project
Create a new Web project on Eclipse, add ACTIVEMQ-dependent jar packages, and start writing two servlets, one for the production message and the other for consuming messages, as in the following code:
Message producer Servlet:
Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJavax.jms.DeliveryMode;ImportJavax.jms.Queue;Importjavax.jms.QueueConnection;Importjavax.jms.QueueConnectionFactory;ImportJavax.jms.QueueSender;Importjavax.jms.QueueSession;Importjavax.jms.Session;ImportJavax.jms.TextMessage;ImportJavax.naming.InitialContext;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Servlet Implementation class Jmstest*/@WebServlet ("/send") Public classSendextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /** * @seeHttpservlet#httpservlet ()*/ PublicSend () {Super(); //TODO auto-generated Constructor stub } /** * @seeHttpservlet#doget (httpservletrequest request, HttpServletResponse * response)*/ protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {printwriter out=Response.getwriter (); Try { //get the initial contextInitialContext context =NewInitialContext (); //Lookup the Queue objectQueue queue = (queue) context.lookup ("Java:comp/env/queue/queue0"); //Lookup The Queue connection factoryQueueconnectionfactory confactory =(queueconnectionfactory) context. Lookup ("Java:comp/env/queue/connectionfactory"); //Create a queue connectionQueueconnection Queconn =confactory.createqueueconnection (); //Create a queue sessionQueuesession quesession = queconn.createqueuesession (false, Session.dups_ok_acknowledge); //Create a queue senderQueuesender 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 messagequesender.send (message); //Print What do we didOut.write ("Message Sent:" +Message.gettext ()); //Close the queue connectionQueconn.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } /** * @seeHttpservlet#dopost (httpservletrequest request, HttpServletResponse * response)*/ protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub }}
Message Consumer servlet:
Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJavax.jms.Queue;Importjavax.jms.QueueConnection;Importjavax.jms.QueueConnectionFactory;ImportJavax.jms.QueueReceiver;Importjavax.jms.QueueSession;Importjavax.jms.Session;ImportJavax.jms.TextMessage;ImportJavax.naming.InitialContext;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Servlet Implementation class Receive*/@WebServlet ("/receive") Public classReceiveextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /** * @seeHttpservlet#httpservlet ()*/ PublicReceive () {Super(); //TODO auto-generated Constructor stub } /** * @seeHttpservlet#doget (httpservletrequest request, HttpServletResponse * response)*/ protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {printwriter out=Response.getwriter (); Try { //get the initial contextInitialContext context =NewInitialContext (); //Lookup the Queue objectQueue queue = (queue) context.lookup ("Java:comp/env/queue/queue0"); //Lookup The Queue connection factoryQueueconnectionfactory confactory =(queueconnectionfactory) context. Lookup ("Java:comp/env/queue/connectionfactory"); //Create a queue connectionQueueconnection Queconn =confactory.createqueueconnection (); //Create a queue sessionQueuesession quesession = queconn.createqueuesession (false, Session.auto_acknowledge); //Create a queue receiverQueueReceiver Quereceiver =quesession.createreceiver (queue); //Start the connectionQueconn.start (); //receive a messageTextMessage message =(TextMessage) quereceiver.receive (); //Print the messageOut.write ("Message Received:" +Message.gettext ()); //Close the queue connectionQueconn.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } /** * @seeHttpservlet#dopost (httpservletrequest request, HttpServletResponse * response)*/ protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub }}
Validation results
Run the Web project in Tomcat, execute the message producer Servlet, return the message to send the success flag, and we can view the message in http://localhost:8161/admin/queues.jsp, as shown in
Continue to execute the message consumer servlet, return message receive success flag, and we can open the Http://localhost:8161/admin/queues.jsp page, found that the message has been missing, as shown in
Code reference: http://howtodoinjava.com/jms/jms-point-to-point-message-example/
Point-to-point message delivery for JMS based on Tomcat + JNDI + ACTIVEMQ