.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
- public class TopicListener implements MessageListener {
- private Connection connection;
- private MessageProducer producer;
- private Session session;
- private int count;
- private long start;
- private Topic topic;
- private Topic control;
- private String url = "tcp://localhost:61616";
- private static MyConsumerFrame frame= new MyConsumerFrame();;
- private static Long countMsg = 1L;
- public static void main(String[] argv) throws Exception {
- TopicListener l = new TopicListener();
- String[] unknown = CommandLineSupport.setOptions(l, argv);
- if (unknown.length > 0) {
- System.out.println("Unknown options: " + Arrays.toString(unknown));
- System.exit(-1);
- }
- l.run();
- }
- public void run() throws JMSException {
- ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
- connection = factory.createConnection();
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- topic = session.createTopic("topictest.messages");
- control = session.createTopic("topictest.control");
- MessageConsumer consumer = session.createConsumer(topic);
- consumer.setMessageListener(this);
- connection.start();
- producer = session.createProducer(control);
- System.out.println("Waiting for messages...");
- }
- private static boolean checkText(Message m, String s) {
- try {
- return m instanceof TextMessage && ((TextMessage)m).getText().equals(s);
- } catch (JMSException e) {
- e.printStackTrace(System.out);
- return false;
- }
- }
- public void onMessage(Message message) {
- if (message instanceof ExitRecord) {
- System.out.println("___________________Object Message!");
- ExitRecord record = (ExitRecord)message;
- Long msgCpuId = record.getCpucardId();
- frame.getTableModle().addRow(new String[]{String.valueOf(countMsg++), String.valueOf(msgCpuId)});
- }
- if (checkText(message, "SHUTDOWN")) {
- try {
- connection.close();
- } catch (Exception e) {
- e.printStackTrace(System.out);
- }
- } else if (checkText(message, "REPORT")) {
- // send a report:
- try {
- long time = System.currentTimeMillis() - start;
- String msg = "Received " + count + " in " + time + "ms";
- producer.send(session.createTextMessage(msg));
- } catch (Exception e) {
- e.printStackTrace(System.out);
- }
- count = 0;
- } else {
- if (count == 0) {
- start = System.currentTimeMillis();
- }
- if (++count % 1000 == 0) {
- System.out.println("Received " + count + " messages.");
- }
- }
- }
- public void setUrl(String url) {
- this.url = url;
- }
- }
- public class TopicPublisher implements MessageListener {
- private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();
- private final Object mutex = new Object();
- private Connection connection;
- private Session session;
- private MessageProducer publisher;
- private Topic topic;
- private Topic control;
- private String url = "tcp://localhost:61616";
- private int size = 256;
- private int subscribers = 1;
- private int remaining;
- private int messages = 10000;
- private long delay;
- private int batch = 2000;
- private byte[] payload;
- public static void main(String[] argv) throws Exception {
- TopicPublisher p = new TopicPublisher();
- String[] unknown = CommandLineSupport.setOptions(p, argv);
- if (unknown.length > 0) {
- System.out.println("Unknown options: " + Arrays.toString(unknown));
- System.exit(-1);
- }
- p.run();
- }
- private void run() throws Exception {
- ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
- connection = factory.createConnection();
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- topic = session.createTopic("topictest.messages");
- control = session.createTopic("topictest.control");
- publisher = session.createProducer(topic);
- publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- payload = new byte[size];
- for (int i = 0; i < size; i++) {
- payload[i] = (byte)DATA[i % DATA.length];
- }
- session.createConsumer(control).setMessageListener(this);
- connection.start();
- long[] times = new long[batch];
- for (int i = 0; i < batch; i++) {
- if (i > 0) {
- Thread.sleep(delay * 1000);
- }
- times[i] = batch(messages);
- System.out.println("Batch " + (i + 1) + " of " + batch + " completed in " + times[i] + " ms.");
- }
- long min = min(times);
- long max = max(times);
- System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max));
- // request shutdown
- publisher.send(session.createTextMessage("SHUTDOWN"));
- connection.stop();
- connection.close();
- }
- private long batch(int msgCount) throws Exception {
- long start = System.currentTimeMillis();
- remaining = subscribers;
- publish();
- waitForCompletion();
- return System.currentTimeMillis() - start;
- }
- private void publish() throws Exception {
- // send events
- BytesMessage msg = session.createBytesMessage();
- msg.writeBytes(payload);
- for (int i = 0; i < messages; i++) {
- publisher.send(msg);
- if ((i + 1) % 1000 == 0) {
- System.out.println("Sent " + (i + 1) + " messages");
- }
- }
- // request report
- publisher.send(session.createTextMessage("REPORT"));
- }
- private void waitForCompletion() throws Exception {
- System.out.println("Waiting for completion...");
- synchronized (mutex) {
- while (remaining > 0) {
- mutex.wait();
- }
- }
- }
- public void onMessage(Message message) {
- synchronized (mutex) {
- System.out.println("Received report " + getReport(message) + " " + --remaining + " remaining");
- if (remaining == 0) {
- mutex.notify();
- }
- }
- }
- Object getReport(Message m) {
- try {
- return ((TextMessage)m).getText();
- } catch (JMSException e) {
- e.printStackTrace(System.out);
- return e.toString();
- }
- }
- static long min(long[] times) {
- long min = times.length > 0 ? times[0] : 0;
- for (int i = 0; i < times.length; i++) {
- min = Math.min(min, times[i]);
- }
- return min;
- }
- static long max(long[] times) {
- long max = times.length > 0 ? times[0] : 0;
- for (int i = 0; i < times.length; i++) {
- max = Math.max(max, times[i]);
- }
- return max;
- }
- static long avg(long[] times, long min, long max) {
- long sum = 0;
- for (int i = 0; i < times.length; i++) {
- sum += times[i];
- }
- sum -= min;
- sum -= max;
- return sum / times.length - 2;
- }
- public void setBatch(int batch) {
- this.batch = batch;
- }
- public void setDelay(long delay) {
- this.delay = delay;
- }
- public void setMessages(int messages) {
- this.messages = messages;
- }
- public void setSize(int size) {
- this.size = size;
- }
- public void setSubscribers(int subscribers) {
- this.subscribers = subscribers;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- }