之因此使用JNDI 是出於通用性考慮,該例子使用JMS規範提供的通用接口,沒有使用具體JMS提供者的接口,這樣能夠保證咱們編寫的程序適用於任何一種JMS實現(ActiveMQ、HornetQ等)。html
什麼是JNDI:JNDI(Java Naming and Directory Interface)是一個標準規範,相似於JDBC,JMS等規範,爲開發人員提供了查找和訪問各類命名和目錄服務的通用、統一的接口。J2EE 規範要求全部 J2EE 容器都要提供 JNDI 規範的實現,所以Tomcat就實現了JNDI 規範。java
找到Tomcat安裝路徑下的conf文件夾,打開context.xml,添加以下配置:web
<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" />
Eclipse上新建web工程,添加ActiveMQ依賴的jar包,而後開始編寫兩個Servlet,一個用於生產消息,另外一個用於消費消息,以下代碼:apache
消息生產者Servlet:session
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 } }
消息消費者Servlet:jsp
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 } }
在Tomcat裏運行該Web工程,執行消息生產者Servlet,返回消息發送成功標誌,同時咱們能夠在http://localhost:8161/admin/queues.jsp查看到該消息,以下圖所示tcp
繼續執行消息消費者Servlet,返回消息接收成功標誌,同時咱們能夠打開http://localhost:8161/admin/queues.jsp頁面,發現剛纔的消息已經不見了,以下圖所示ide
配置鏈接工廠和話題:post
<Resource name="topic/connectionFactory" auth="Container" type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS Connection Factory" factory="org.apache.activemq.jndi.JNDIReferenceFactory" brokerURL="failover:(tcp://localhost:61616)?initialReconnectDelay=100&maxReconnectAttempts=5" brokerName="LocalActiveMQBroker" useEmbeddedBroker="false" /> <Resource name="topic/topic0" auth="Container" type="org.apache.activemq.command.ActiveMQTopic" description="My Topic" factory="org.apache.activemq.jndi.JNDIReferenceFactory" physicalName="TestTopic" />
新建一個發佈者Servlet:url
package pubSub; import java.io.IOException; import java.io.PrintWriter; 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; import javax.jms.Topic; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.TopicPublisher; import javax.jms.DeliveryMode; import javax.jms.TopicSession; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; /** * Servlet implementation class JMSTest */ @WebServlet("/Publish") public class Publisher extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Publisher() { 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 ctx = new InitialContext(); // lookup the topic object Topic topic = (Topic) ctx.lookup("java:comp/env/topic/topic0"); // lookup the topic connection factory TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx .lookup("java:comp/env/topic/connectionFactory"); // create a topic connection TopicConnection topicConn = connFactory.createTopicConnection(); // create a topic session TopicSession topicSession = topicConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // create a topic publisher TopicPublisher topicPublisher = topicSession.createPublisher(topic); topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // create the "Hello World" message TextMessage message = topicSession.createTextMessage(); message.setText("Hello World"); // publish the messages topicPublisher.publish(message); // print what we did out.write("Message published: " + message.getText()); // close the topic connection topicConn.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:
package pubSub; import java.io.IOException; import java.io.PrintWriter; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; 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("/Subscribe") public class Subscriber extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Subscriber() { 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 ctx = new InitialContext(); // lookup the topic object Topic topic = (Topic) ctx.lookup("java:comp/env/topic/topic0"); // lookup the topic connection factory TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx .lookup("java:comp/env/topic/connectionFactory"); // create a topic connection TopicConnection topicConn = connFactory.createTopicConnection(); // create a topic session TopicSession topicSession = topicConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // create a topic subscriber TopicSubscriber topicSubscriber = topicSession .createSubscriber(topic); // start the connection topicConn.start(); // receive the message TextMessage message = (TextMessage) topicSubscriber.receive(); // print the message out.write("Message received: " + message.getText()); // close the topic connection topicConn.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 } }
運行Web工程,分別打開多個標籤訪問訂閱servlet,而後訪問發佈servlet,結果以下:
在訂閱者訂閱消息的時候,一開始沒接收到消息,一旦發佈者發佈消息後,訂閱者立刻收到消息。