JMS實戰

 

JMS實戰


.JMS介紹 
    JMS源於企業應用對於消息中間件的需求,使應用程序可以通過消息進行異步處理而互不影響。Sun公司和它的合作伙伴設計的JMS API定義了一組公共的應用程序接口和相應語法,使得Java程序能夠和其他消息組件進行通信。JMS有四個組成部分:JMS服務提供者、消息管理對象、消息的生產者消費者和消息本身。 
1)JMS服務提供者實現消息隊列和通知,同時實現消息管理的API。JMS已經是J2EE API的一部分,J2EE服務器都提供JMS服務。 
2) 消息管理對象提供對消息進行操作的API。JMS API中有兩個消息管理對象:創建jms連接使用的工廠(ConnectionFactory)和目的地(Destination),根據消息的消費方式的不同ConnectionFactory可以分爲QueueConnectionFactory和TopicConnectionFactory,目的地(Destination)可以分爲隊列(Queue)和主題(Topic)兩種。 
3)消息的生產者和消費者。消息的產生由JMS的客戶端完成,JMS服務提供者負責管理這些消息,消息的消費者可以接收消息。消息的生產者可以分爲――點對點消息發佈者(P2P)和主題消息發佈者(TopicPublisher)。所以,消息的消費者分爲兩類:主題消息的訂閱者(TopicSubscriber)和點對點消息的接收者(queue receiver) 
4)消息。消息是服務提供者和客戶端之間傳遞信息所使用的信息單元。JMS消息由以下三部分組成: 
  消息頭(header)――JMS消息頭包含了許多字段,它們是消息發送後由JMS提供者或消息發送者產生,用來表示消息、設置優先權和失效時間等等,並且爲消息確定路由。 
  屬性(property)――用來添加刪除消息頭以外的附加信息。 
  消息體(body)――JMS中定義了5種消息體:ByteMessage、MapMessage、ObjectMessage、StreamMessage和TextMessage。 

2.Messages 通信方式 
上面提到JMS通信方式分爲點對點通信和發佈/訂閱方式 
1)點對點方式(point-to-point) 
   點對點的消息發送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存貯消息,Sneder 發送消息,receive接收消息.具體點就是Sender Client發送Message Queue ,而 receiver Cliernt從Queue中接收消息和"發送消息已接受"到Quere,確認消息接收。消息發送客戶端與接收客戶端沒有時間上的依賴,發送客戶端可以在任何時刻發送信息到Queue,而不需要知道接收客戶端是不是在運行 
2)發佈/訂閱 方式(publish/subscriber Messaging) 
    發佈/訂閱方式用於多接收客戶端的方式.作爲發佈訂閱的方式,可能存在多個接收客戶端,並且接收端客戶端與發送客戶端存在時間上的依賴。一個接收端只能接收他創建以後發送客戶端發送的信息。作爲subscriber ,在接收消息時有兩種方法,destination的receive方法,和實現message listener 接口的onMessage 方法。 

3.爲什麼選用ActiveMQ 
   1)ActiveMQ是一個開放源碼 
   2)基於Apache 2.0 licenced 發佈並實現了JMS 1.1。 
   3)ActiveMQ現在已經和作爲很多項目的異步消息通信核心了 
   4)在很多中小型項目中採用ActiveMQ+SPRING+TOMCAT開發模式。 

4.編程模式 
4.1消息產生者向JMS發送消息的步驟 
(1)創建連接使用的工廠類JMS ConnectionFactory 
(2)使用管理對象JMS ConnectionFactory建立連接Connection 
(3)使用連接Connection 建立會話Session 
(4)使用會話Session和管理對象Destination創建消息生產者MessageSender 
(5)使用消息生產者MessageSender發送消息 
4.2消息消費者從JMS接受消息的步驟 
(1)創建連接使用的工廠類JMS ConnectionFactory 
(2)使用管理對象JMS ConnectionFactory建立連接Connection 
(3)使用連接Connection 建立會話Session 
(4)使用會話Session和管理對象Destination創建消息消費者MessageReceiver 
(5)使用消息消費者MessageReceiver接受消息,需要用setMessageListener將MessageListener接口綁定到MessageReceiver 
消息消費者必須實現了MessageListener接口,需要定義onMessage事件方法。 

5.ActiveMQ運行 
ActiveMQ5.0版本默認啓動時,啓動了內置的jetty服務器,提供一個demo應用和用於監控ActiveMQ的admin應用。運行%activemq_home%bin/目錄下的 activemq.bat , 之後你會看見如下一段話表示啓動成功。 
打開http://localhost:8161/admin/queues.jsp ,可以查看相應的queue中是否有消息

 

服務端TopicPublisher.java

6 可用的例子

客戶端:TopicListener.java

[java] view plaincopy
  1. public class TopicListener implements MessageListener {  
  2.   
  3.     private Connection connection;  
  4.     private MessageProducer producer;  
  5.     private Session session;  
  6.     private int count;  
  7.     private long start;  
  8.     private Topic topic;  
  9.     private Topic control;  
  10.   
  11.     private String url = "tcp://localhost:61616";  
  12.       
  13.     private static MyConsumerFrame frame= new MyConsumerFrame();;  
  14.       
  15.     private static Long countMsg = 1L;  
  16.   
  17.     public static void main(String[] argv) throws Exception {  
  18.   
  19.         TopicListener l = new TopicListener();  
  20.         String[] unknown = CommandLineSupport.setOptions(l, argv);  
  21.         if (unknown.length > 0) {  
  22.             System.out.println("Unknown options: " + Arrays.toString(unknown));  
  23.             System.exit(-1);  
  24.         }  
  25.         l.run();  
  26.     }  
  27.   
  28.     public void run() throws JMSException {  
  29.         ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);  
  30.         connection = factory.createConnection();  
  31.         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  32.         topic = session.createTopic("topictest.messages");  
  33.         control = session.createTopic("topictest.control");  
  34.   
  35.         MessageConsumer consumer = session.createConsumer(topic);  
  36.         consumer.setMessageListener(this);  
  37.   
  38.         connection.start();  
  39.   
  40.         producer = session.createProducer(control);  
  41.         System.out.println("Waiting for messages...");  
  42.     }  
  43.   
  44.     private static boolean checkText(Message m, String s) {  
  45.         try {  
  46.             return m instanceof TextMessage && ((TextMessage)m).getText().equals(s);  
  47.         } catch (JMSException e) {  
  48.             e.printStackTrace(System.out);  
  49.             return false;  
  50.         }  
  51.     }  
  52.   
  53.     public void onMessage(Message message) {  
  54.         if (message instanceof ExitRecord) {  
  55.             System.out.println("___________________Object Message!");  
  56.             ExitRecord record = (ExitRecord)message;  
  57.             Long msgCpuId = record.getCpucardId();  
  58.             frame.getTableModle().addRow(new String[]{String.valueOf(countMsg++), String.valueOf(msgCpuId)});  
  59.         }  
  60.           
  61.         if (checkText(message, "SHUTDOWN")) {  
  62.   
  63.             try {  
  64.                 connection.close();  
  65.             } catch (Exception e) {  
  66.                 e.printStackTrace(System.out);  
  67.             }  
  68.   
  69.         } else if (checkText(message, "REPORT")) {  
  70.             // send a report:  
  71.             try {  
  72.                 long time = System.currentTimeMillis() - start;  
  73.                 String msg = "Received " + count + " in " + time + "ms";  
  74.                 producer.send(session.createTextMessage(msg));  
  75.             } catch (Exception e) {  
  76.                 e.printStackTrace(System.out);  
  77.             }  
  78.             count = 0;  
  79.   
  80.         } else {  
  81.   
  82.             if (count == 0) {  
  83.                 start = System.currentTimeMillis();  
  84.             }  
  85.   
  86.             if (++count % 1000 == 0) {  
  87.                 System.out.println("Received " + count + " messages.");  
  88.             }  
  89.         }  
  90.     }  
  91.   
  92.     public void setUrl(String url) {  
  93.         this.url = url;  
  94.     }  
  95.   
  96. }  

[java] view plaincopy
  1. public class TopicPublisher implements MessageListener {  
  2.   
  3.     private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();  
  4.   
  5.     private final Object mutex = new Object();  
  6.     private Connection connection;  
  7.     private Session session;  
  8.     private MessageProducer publisher;  
  9.     private Topic topic;  
  10.     private Topic control;  
  11.   
  12.     private String url = "tcp://localhost:61616";  
  13.     private int size = 256;  
  14.     private int subscribers = 1;  
  15.     private int remaining;  
  16.     private int messages = 10000;  
  17.     private long delay;  
  18.     private int batch = 2000;  
  19.   
  20.     private byte[] payload;  
  21.   
  22.     public static void main(String[] argv) throws Exception {  
  23.         TopicPublisher p = new TopicPublisher();  
  24.         String[] unknown = CommandLineSupport.setOptions(p, argv);  
  25.         if (unknown.length > 0) {  
  26.             System.out.println("Unknown options: " + Arrays.toString(unknown));  
  27.             System.exit(-1);  
  28.         }  
  29.         p.run();  
  30.     }  
  31.   
  32.     private void run() throws Exception {  
  33.         ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);  
  34.         connection = factory.createConnection();  
  35.         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  36.         topic = session.createTopic("topictest.messages");  
  37.         control = session.createTopic("topictest.control");  
  38.   
  39.         publisher = session.createProducer(topic);  
  40.         publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);  
  41.   
  42.         payload = new byte[size];  
  43.         for (int i = 0; i < size; i++) {  
  44.             payload[i] = (byte)DATA[i % DATA.length];  
  45.         }  
  46.   
  47.         session.createConsumer(control).setMessageListener(this);  
  48.         connection.start();  
  49.   
  50.         long[] times = new long[batch];  
  51.         for (int i = 0; i < batch; i++) {  
  52.             if (i > 0) {  
  53.                 Thread.sleep(delay * 1000);  
  54.             }  
  55.             times[i] = batch(messages);  
  56.             System.out.println("Batch " + (i + 1) + " of " + batch + " completed in " + times[i] + " ms.");  
  57.         }  
  58.   
  59.         long min = min(times);  
  60.         long max = max(times);  
  61.         System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max));  
  62.   
  63.         // request shutdown  
  64.         publisher.send(session.createTextMessage("SHUTDOWN"));  
  65.   
  66.         connection.stop();  
  67.         connection.close();  
  68.     }  
  69.   
  70.     private long batch(int msgCount) throws Exception {  
  71.         long start = System.currentTimeMillis();  
  72.         remaining = subscribers;  
  73.         publish();  
  74.         waitForCompletion();  
  75.         return System.currentTimeMillis() - start;  
  76.     }  
  77.   
  78.     private void publish() throws Exception {  
  79.   
  80.         // send events  
  81.         BytesMessage msg = session.createBytesMessage();  
  82.         msg.writeBytes(payload);  
  83.         for (int i = 0; i < messages; i++) {  
  84.             publisher.send(msg);  
  85.             if ((i + 1) % 1000 == 0) {  
  86.                 System.out.println("Sent " + (i + 1) + " messages");  
  87.             }  
  88.         }  
  89.   
  90.         // request report  
  91.         publisher.send(session.createTextMessage("REPORT"));  
  92.     }  
  93.   
  94.     private void waitForCompletion() throws Exception {  
  95.         System.out.println("Waiting for completion...");  
  96.         synchronized (mutex) {  
  97.             while (remaining > 0) {  
  98.                 mutex.wait();  
  99.             }  
  100.         }  
  101.     }  
  102.   
  103.     public void onMessage(Message message) {  
  104.         synchronized (mutex) {  
  105.             System.out.println("Received report " + getReport(message) + " " + --remaining + " remaining");  
  106.             if (remaining == 0) {  
  107.                 mutex.notify();  
  108.             }  
  109.         }  
  110.     }  
  111.   
  112.     Object getReport(Message m) {  
  113.         try {  
  114.             return ((TextMessage)m).getText();  
  115.         } catch (JMSException e) {  
  116.             e.printStackTrace(System.out);  
  117.             return e.toString();  
  118.         }  
  119.     }  
  120.   
  121.     static long min(long[] times) {  
  122.         long min = times.length > 0 ? times[0] : 0;  
  123.         for (int i = 0; i < times.length; i++) {  
  124.             min = Math.min(min, times[i]);  
  125.         }  
  126.         return min;  
  127.     }  
  128.   
  129.     static long max(long[] times) {  
  130.         long max = times.length > 0 ? times[0] : 0;  
  131.         for (int i = 0; i < times.length; i++) {  
  132.             max = Math.max(max, times[i]);  
  133.         }  
  134.         return max;  
  135.     }  
  136.   
  137.     static long avg(long[] times, long min, long max) {  
  138.         long sum = 0;  
  139.         for (int i = 0; i < times.length; i++) {  
  140.             sum += times[i];  
  141.         }  
  142.         sum -= min;  
  143.         sum -= max;  
  144.         return sum / times.length - 2;  
  145.     }  
  146.   
  147.     public void setBatch(int batch) {  
  148.         this.batch = batch;  
  149.     }  
  150.   
  151.     public void setDelay(long delay) {  
  152.         this.delay = delay;  
  153.     }  
  154.   
  155.     public void setMessages(int messages) {  
  156.         this.messages = messages;  
  157.     }  
  158.   
  159.     public void setSize(int size) {  
  160.         this.size = size;  
  161.     }  
  162.   
  163.     public void setSubscribers(int subscribers) {  
  164.         this.subscribers = subscribers;  
  165.     }  
  166.   
  167.     public void setUrl(String url) {  
  168.         this.url = url;  
  169.     }  
  170. }  

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