ActiveMq-JMS簡單實例使用tomcat

原文地址:http://madfroghe.iteye.com/blog/927637

一、修改配置文件

1.1 修改Tomcatconf/context.xml文件:

<context></context>節點中添加以下內容

 

  1. <Resource 
  2.         name="jms/FailoverConnectionFactory" 
  3.         auth="Container" 
  4.         type="org.apache.activemq.ActiveMQConnectionFactory" 
  5.         description="JMS Connection Factory" 
  6.         factory="org.apache.activemq.jndi.JNDIReferenceFactory" 
  7.     brokerURL="failover:(tcp://localhost:61616)?initialReconnectDelay=100&amp;maxReconnectAttempts=5" 
  8.         brokerName="localhost" 
  9.         useEmbeddedBroker="false"/> 
  10.     <Resource 
  11.         name="jms/NormalConnectionFactory" 
  12.         auth="Container" 
  13.         type="org.apache.activemq.ActiveMQConnectionFactory" 
  14.         description="JMS Connection Factory" 
  15.         factory="org.apache.activemq.jndi.JNDIReferenceFactory" 
  16.         brokerURL="tcp://localhost:61616" 
  17.         brokerName="localhost" 
  18.         useEmbeddedBroker="false"/> 
  19.     <Resource name="jms/topic/MyTopic" 
  20.         auth="Container" 
  21.         type="org.apache.activemq.command.ActiveMQTopic" 
  22.         factory="org.apache.activemq.jndi.JNDIReferenceFactory" 
  23.         physicalName="MY.TEST.FOO"/> 
  24.     <Resource name="jms/queue/MyQueue" 
  25.         auth="Container" 
  26.         type="org.apache.activemq.command.ActiveMQQueue" 
  27.         factory="org.apache.activemq.jndi.JNDIReferenceFactory" 
  28.         physicalName="MY.TEST.FOO.QUEUE"/> 

二、詳細示例

2.1 監聽類

  1. package com.flvcd.servlet; 
  2.  
  3. import java.io.*; 
  4. import javax.servlet.*; 
  5. import javax.servlet.http.*; 
  6. import javax.naming.*; 
  7. import javax.jms.*; 
  8. import org.apache.activemq.ActiveMQConnectionFactory; 
  9.  
  10. public class JMSListener extends HttpServlet implements MessageListener { 
  11.     /** 初始化jms連接,創建topic監聽器 */ 
  12.     public void init(ServletConfig config) throws ServletException { 
  13.         try { 
  14.             InitialContext initCtx = new InitialContext(); 
  15.             Context envContext = (Context) initCtx.lookup("java:comp/env"); 
  16.             ConnectionFactory connectionFactory = (ConnectionFactory) envContext 
  17.                     .lookup("jms/FailoverConnectionFactory"); 
  18.             Connection connection = connectionFactory.createConnection(); 
  19.             connection.setClientID("MyClient"); 
  20.             Session jmsSession = connection.createSession(false
  21.                     Session.AUTO_ACKNOWLEDGE); 
  22.             // 普通消息訂閱者,無法接收持久消息 //MessageConsumer consumer = 
  23.             // jmsSession.createConsumer((Destination) 
  24.             // envContext.lookup("jms/topic/MyTopic")); 
  25.             // //基於Topic創建持久的消息訂閱者,前提:Connection必須指定一個唯一的clientId,當前爲MyClient 
  26.         TopicSubscriber consumer=jmsSession.createDurableSubscriber((Topic)envContext.lookup("jms/topic/MyTopic"), "MySub"); 
  27.             consumer.setMessageListener(this); 
  28.             connection.start(); 
  29.         } catch (NamingException e) { 
  30.             e.printStackTrace(); 
  31.         } catch (JMSException e) { 
  32.             e.printStackTrace(); 
  33.         } 
  34.     } 
  35.  
  36.     /** 接收消息,做對應處理 */ 
  37.     public void onMessage(Message message) { 
  38.         if (checkText(message, "RefreshArticleId") != null) { 
  39.             String articleId = checkText(message, "RefreshArticleId"); 
  40.             System.out.println("接收刷新文章消息,開始刷新文章ID=" + articleId); 
  41.         } else if (checkText(message, "RefreshThreadId") != null) { 
  42.             String threadId = checkText(message, "RefreshThreadId"); 
  43.             System.out.println("接收刷新論壇帖子消息,開始刷新帖子ID=" + threadId); 
  44.         } else { 
  45.             System.out.println("接收普通消息,不做任何處理!"); 
  46.         } 
  47.     } 
  48.  
  49.     private static String checkText(Message m, String s) { 
  50.         try { 
  51.             return m.getStringProperty(s); 
  52.         } catch (JMSException e) { 
  53.             e.printStackTrace(System.out); 
  54.             return null
  55.         } 
  56.     } 

2.2 發佈類

  1. package com.flvcd.servlet; 
  2.  
  3. import java.io.IOException; 
  4. import java.io.PrintWriter; 
  5.  
  6. import javax.jms.Connection; 
  7. import javax.jms.ConnectionFactory; 
  8. import javax.jms.DeliveryMode; 
  9. import javax.jms.Destination; 
  10. import javax.jms.JMSException; 
  11. import javax.jms.Message; 
  12. import javax.jms.MessageListener; 
  13. import javax.jms.MessageProducer; 
  14. import javax.jms.Session; 
  15. import javax.naming.Context; 
  16. import javax.naming.InitialContext; 
  17. import javax.naming.NamingException; 
  18. import javax.servlet.ServletException; 
  19. import javax.servlet.http.HttpServlet; 
  20. import javax.servlet.http.HttpServletRequest; 
  21. import javax.servlet.http.HttpServletResponse; 
  22.  
  23. public class MyPublish extends HttpServlet implements MessageListener { 
  24.      
  25.      
  26.     //定義初始化所需要的變量 
  27.     private InitialContext initCtx; 
  28.     private Context envContext; 
  29.     private ConnectionFactory connectionFactory; 
  30.     private Connection connection; 
  31.     private Session jmsSession; 
  32.     private MessageProducer producer; 
  33.      
  34.      
  35.     public void onMessage(Message message) { 
  36.         // TODO Auto-generated method stub 
  37.  
  38.     } 
  39.  
  40.     /** 
  41.      * Constructor of the object. 
  42.      */ 
  43.     public MyPublish() { 
  44.         super(); 
  45.     } 
  46.  
  47.     /** 
  48.      * Destruction of the servlet. <br> 
  49.      */ 
  50.     public void destroy() { 
  51.         super.destroy(); // Just puts "destroy" string in log 
  52.         // Put your code here 
  53.     } 
  54.  
  55.     /** 
  56.      * The doGet method of the servlet. <br> 
  57.      * 
  58.      * This method is called when a form has its tag value method equals to get. 
  59.      *  
  60.      * @param request the request send by the client to the server 
  61.      * @param response the response send by the server to the client 
  62.      * @throws ServletException if an error occurred 
  63.      * @throws IOException if an error occurred 
  64.      */ 
  65.     public void doGet(HttpServletRequest request, HttpServletResponse response) 
  66.             throws ServletException, IOException { 
  67.  
  68.     doPost(request, response); 
  69.     } 
  70.  
  71.     /** 
  72.      * The doPost method of the servlet. <br> 
  73.      * 
  74.      * This method is called when a form has its tag value method equals to post. 
  75.      *  
  76.      * @param request the request send by the client to the server 
  77.      * @param response the response send by the server to the client 
  78.      * @throws ServletException if an error occurred 
  79.      * @throws IOException if an error occurred 
  80.      */ 
  81.     public void doPost(HttpServletRequest request, HttpServletResponse response) 
  82.             throws ServletException, IOException { 
  83.         String content=request.getParameter("content"); 
  84.         //設置持久方式 
  85.         try { 
  86.             producer.setDeliveryMode(DeliveryMode.PERSISTENT); 
  87.             Message testMessage = jmsSession.createMessage(); 
  88.             // 發佈刷新文章消息 
  89.             testMessage.setStringProperty("RefreshArticleId", content); 
  90.             producer.send(testMessage); 
  91.             // 發佈刷新帖子消息 
  92.             testMessage.clearProperties(); 
  93.             testMessage.setStringProperty("RefreshThreadId", content); 
  94.             producer.send(testMessage); 
  95.         } catch (Exception e) { 
  96.             e.printStackTrace(); 
  97.         } 
  98.          
  99.          
  100.     } 
  101.  
  102.     /** 
  103.      * Initialization of the servlet. <br> 
  104.      * 
  105.      * @throws ServletException if an error occurs 
  106.      */ 
  107.     public void init() throws ServletException { 
  108.         // Put your code here 
  109.         try { 
  110.             initCtx = new InitialContext(); 
  111.             envContext = (Context) initCtx.lookup("java:comp/env"); 
  112.             connectionFactory = (ConnectionFactory) envContext.lookup("jms/NormalConnectionFactory"); 
  113.             connection = connectionFactory.createConnection(); 
  114.             jmsSession = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); 
  115.             producer = jmsSession.createProducer((Destination) envContext.lookup("jms/topic/MyTopic")); 
  116.  
  117.         } catch (NamingException e) { 
  118.             e.printStackTrace(); 
  119.         } catch (JMSException e) { 
  120.             e.printStackTrace(); 
  121.         } 
  122.     } 

2.3 MyPublish.jsp

  1. <form action="myPublish.do"
  2.     <input type="text" name="content" /> 
  3.     <input type="submit" value="提交" > 
  4. /form> 

2.4 web.xml也需要相應配置,詳細見附件。

關鍵代碼:

  1. <servlet> 
  2. <servlet-name>jms-listener</servlet-name> 
  3. <servlet-class> 
  4. com.flvcd.servlet.JMSListener 
  5. </servlet-class> 
  6. <load-on-startup>1</load-on-startup> 
  7. </servlet> 

因上傳限制附件中缺少ActiveMq.jar,請自行下載。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章