分佈式--ActiveMQ 消息中間件(一) https://www.jianshu.com/p/8b9bfe865e38

1. ActiveMQ

1). ActiveMQ

ActiveMQ是Apache所提供的一個開源的消息系統,徹底採用Java來實現,所以,它能很好地支持J2EE提出的JMS(Java Message Service,即Java消息服務)規範。JMS是一組Java應用程序接口,它提供消息的建立、發送、讀取等一系列服務。JMS提供了一組公共應用程序接口和響應的語法,相似於Java數據庫的統一訪問接口JDBC,它是一種與廠商無關的API,使得Java程序可以與不一樣廠商的消息組件很好地進行通訊。html

2). Java Message Service(JMS)

JMS支持兩種消息發送和接收模型。java

  • 一種稱爲P2P(Ponit to Point)模型,即採用點對點的方式發送消息。P2P模型是基於隊列的,消息生產者發送消息到隊列,消息消費者從隊列中接收消息,隊列的存在使得消息的異步傳輸稱爲可能,P2P模型在點對點的狀況下進行消息傳遞時採用。linux


     
    圖1.png
  • 另外一種稱爲Pub/Sub(Publish/Subscribe,即發佈-訂閱)模型,發佈-訂閱模型定義瞭如何向一個內容節點發布和訂閱消息,這個內容節點稱爲topic(主題)。主題能夠認爲是消息傳遞的中介,消息發佈這將消息發佈到某個主題,而消息訂閱者則從主題訂閱消息。主題使得消息的訂閱者與消息的發佈者互相保持獨立,不須要進行接觸便可保證消息的傳遞,發佈-訂閱模型在消息的一對多廣播時採用。git


     
    圖2.png
3). JMS術語
  • Provider/MessageProvider:生產者
  • Consumer/MessageConsumer:消費者
  • PTP:Point To Point,點對點通訊消息模型
  • Pub/Sub:Publish/Subscribe,發佈訂閱消息模型
  • Queue:隊列,目標類型之一,和PTP結合
  • Topic:主題,目標類型之一,和Pub/Sub結合
  • ConnectionFactory:鏈接工廠,JMS用它建立鏈接
  • Connnection:JMS Client到JMS Provider的鏈接
  • Destination:消息目的地,由Session建立
  • Session:會話,由Connection建立,實質上就是發送、接受消息的一個線程,所以生產者、消費者都是Session建立的
4). ActiveMQ下載
 
圖3.png
  • bin (windows下面的bat(分3二、64位)和unix/linux下面的sh)
  • conf (activeMQ配置目錄,包含最基本的activeMQ配置文件)
  • data (默認是空的)
  • docs (index,replease版本里面沒有文檔,-.-b不知道爲啥不帶)
  • example (幾個例子)
  • lib (activemMQ使用到的lib)
  • webapps 注意ActiveMQ自帶Jetty提供Web管控臺
  • webapps-demo 示例
  • activemq-all-5.15.3.jar
  • LICENSE.txt
  • README.txt
5). 配置
  • Web控制檯帳號和密碼(apache-activemq-5.15.3\conf)
     
    圖4.png
  • 網絡端口(apache-activemq-5.15.3\conf)--默認爲8161
     
    圖5.png
6). 啓動

\apache-activemq-5.15.3\bin\win64\目錄下雙擊activemq.bat文件,在瀏覽器中輸入http://localhost:8161/admin/, 用戶名和密碼輸入admin便可
web

 
圖6.png

 

7). 消息中間件(MOM:Message Orient middleware)

消息中間件有不少的用途和優勢:數據庫

  • 1 將數據從一個應用程序傳送到另外一個應用程序,或者從軟件的一個模塊傳送到另一個模塊;
    1. 負責創建網絡通訊的通道,進行數據的可靠傳送。
    1. 保證數據不重發,不丟失
    1. 可以實現跨平臺操做,可以爲不一樣操做系統上的軟件集成技工數據傳送服務
8).什麼狀況下使用ActiveMQ?
  • 多個項目之間集成
    (1) 跨平臺
    (2) 多語言
    (3) 多項目
  • 下降系統間模塊的耦合度,解耦
    (1) 軟件擴展性
  • 系統先後端隔離
    (1) 先後端隔離,屏蔽高安全區

2. ActiveMQ 示例

1). P2P 示例

I. 導包--activemq-all-5.15.3.jar
II. Producerapache

/** * 定義消息的生產者 * @author mazaiting */ public class Producer { // 用戶名 private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; // 密碼 private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; // 連接 private static final String BROKENURL = ActiveMQConnection.DEFAULT_BROKER_URL; /** * 定義消息併發送,等待消息的接收者(消費者)消費此消息 * @param args * @throws JMSException */ public static void main(String[] args) throws JMSException { // 消息中間件的連接工廠 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory( USERNAME, PASSWORD, BROKENURL); // 鏈接 Connection connection = null; // 會話 Session session = null; // 消息的目的地 Destination destination = null; // 消息生產者 MessageProducer messageProducer = null; try { // 經過鏈接工廠獲取連接 connection = connectionFactory.createConnection(); // 建立會話,進行消息的發送 // 參數一:是否啓用事務 // 參數二:設置自動簽收 session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); // 建立消息隊列 destination = session.createQueue("talkWithMo"); // 建立一個消息生產者 messageProducer = session.createProducer(destination); // 設置持久化/非持久化, 若是非持久化,MQ重啓後可能後致使消息丟失 messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 模擬發送消息 for (int i = 0; i < 5; i++) { TextMessage textMessage = session.createTextMessage("給媽媽發送的消息:"+i); System.out.println("textMessage: " + textMessage); messageProducer.send(textMessage); } // 若是設置了事務,會話就必須提交 session.commit(); } catch (JMSException e) { e.printStackTrace(); } finally { if (null != connection) { connection.close(); } } } } 

III. Consumerwindows

/** * 定義消息的消費者 * @author mazaiting */ public class Consumer { // 用戶名 private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; // 密碼 private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; // 連接 private static final String BROKENURL = ActiveMQConnection.DEFAULT_BROKER_URL; /** * 接收消息 * @param args * @throws JMSException */ public static void main(String[] args) throws JMSException { // 消息中間件的連接工廠 ConnectionFactory connectionFactory = null; // 連接 Connection connection = null; // 會話 Session session = null; // 消息的目的地 Destination destination = null; // 消息的消費者 MessageConsumer messageConsumer = null; // 實例化連接工廠,建立一個連接 connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKENURL); try { // 經過工廠獲取連接 connection = connectionFactory.createConnection(); // 啓動連接 connection.start(); // 建立會話,進行消息的接收 session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); // 建立消息隊列 destination = session.createQueue("talkWithMo"); // 建立一個消息的消費者 messageConsumer = session.createConsumer(destination); // 模擬接收消息 while (true) { TextMessage textMessage = (TextMessage) messageConsumer.receive(10000); if (null != textMessage) { System.out.println("收到消息: " + textMessage); } else { break; } } // 提交 session.commit(); } catch (JMSException e) { e.printStackTrace(); } finally { if (null != connection) { connection.close(); } } } } 

IV. 測試後端

  • 先運行生產者Producer瀏覽器


     
    圖7.png

ActiveMQ控制檯


 
圖8.png
  • 再運行消費者Consumer


     
    圖9.png

    ActiveMQ控制檯


     
    圖10.png

V. 消息類型

  • StreamMessage Java原始值的數據流
  • MapMessage 一套名稱-鍵值對
  • TextMessage 一個字符串對象
  • ObjectMessage 一個序列號的Java對象
  • BytesMessage 一個未解釋字節的數據流
    VI. 控制檯 Queue
  • Messages Enqueued:表示生產了多少條消息,記作P
  • Messages Dequeued:表示消費了多少條消息,記作C
  • Number Of Consumers:表示在該隊列上還有多少消費者在等待接受消息
  • Number Of Pending Messages:表示還有多少條消息沒有被消費,其實是表示消息的積壓程度,就是P-C
    VII. 簽收
    簽收就是消費者接受到消息後,須要告訴消息服務器,我收到消息了。當消息服務器收到回執後,本條消息將失效。所以簽收將對PTP模式產生很大影響。若是消費者收到消息後,並不簽收,那麼本條消息繼續有效,極可能會被其餘消費者消費掉!
  • AUTO_ACKNOWLEDGE:表示在消費者receive消息的時候自動的簽收
  • CLIENT_ACKNOWLEDGE:表示消費者receive消息後必須手動的調用acknowledge()方法進行簽收
  • DUPS_OK_ACKNOWLEDGE:籤不簽收無所謂了,只要消費者可以容忍重複的消息接受,固然這樣會下降Session的開銷
2). request/reply模型

I. 實現思路


 
圖11.png

Client的Producer發出一個JMS message形式的request,request上附加了一些額外的屬性:

  • correlation ID(用來和返回的correlation ID對比進行驗證),
  • JMSReplyTo屬性(放置jms message的destination,這樣worker的Consumer得到jms message就能獲得destination)

Worker的consumer收到requset,處理request並用producer發出reply,destination就從requset的JMSReplyTo屬性中獲得。

II. Server代碼

public class Server implements MessageListener { // 經紀人連接 private static final String BROKER_URL = "tcp://localhost:61616"; // 請求隊列 private static final String REQUEST_QUEUE = "requestQueue"; // 經紀人服務 private BrokerService brokerService; // 會話 private Session session; // 生產者 private MessageProducer producer; // 消費者 private MessageConsumer consumer; private void start() throws Exception { createBroker(); setUpConsumer(); } /** * 建立經紀人 * @throws Exception */ private void createBroker() throws Exception { // 建立經紀人服務 brokerService = new BrokerService(); // 設置是否持久化 brokerService.setPersistent(false); // 設置是否使用JMX brokerService.setUseJmx(false); // 添加連接 brokerService.addConnector(BROKER_URL); // 啓動 brokerService.start(); } /** * 設置消費者 * @throws JMSException */ private void setUpConsumer() throws JMSException { // 建立鏈接工廠 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL); // 建立鏈接 Connection connection = connectionFactory.createConnection(); // 啓動鏈接 connection.start(); // 建立Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 建立隊列 Destination adminQueue = session.createQueue(REQUEST_QUEUE); // 建立生產者 producer = session.createProducer(null); // 設置持久化模式 producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 建立消費者 consumer = session.createConsumer(adminQueue); // 消費者設置消息監聽 consumer.setMessageListener(this); } public void stop() throws Exception { producer.close(); consumer.close(); session.close(); brokerService.stop(); } @Override public void onMessage(Message message) { try { // 建立新消息 TextMessage response = this.session.createTextMessage(); // 判斷消息是不是文本消息 if (message instanceof TextMessage) { // 強轉爲文本消息 TextMessage textMessage = (TextMessage) message; // 獲取消息內容 String text = textMessage.getText(); // 設置消息 response.setText(handleRequest(text)); } response.setJMSCorrelationID(message.getJMSCorrelationID()); producer.send(message.getJMSReplyTo(), response); } catch (JMSException e) { e.printStackTrace(); } } /** * 構建消息內容 * @param text 文本 * @return */ private String handleRequest(String text) { return "Response to '" + text + "'"; } public static void main(String[] args) throws Exception { Server server = new Server(); // 啓動 server.start(); System.out.println(); System.out.println("Press any key to stop the server"); System.out.println(); System.in.read(); server.stop(); } } 

III. Client代碼

public class Client implements MessageListener { // 經紀人連接 private static final String BROKER_URL = "tcp://localhost:61616"; // 請求隊列 private static final String REQUEST_QUEUE = "requestQueue"; // 鏈接 private Connection connection; // 會話 private Session session; // 生產者 private MessageProducer producer; // 消費者 private MessageConsumer consumer; // 請求隊列 private Queue tempDest; public void start() throws JMSException { // 鏈接工廠 ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(BROKER_URL); // 建立鏈接 connection = activeMQConnectionFactory.createConnection(); // 開啓鏈接 connection.start(); // 建立會話 session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 建立隊列 Destination adminQueue = session.createQueue(REQUEST_QUEUE); // 建立生產者 producer = session.createProducer(adminQueue); // 設置持久化模式 producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 建立模板隊列 tempDest = session.createTemporaryQueue(); // 建立消費者 consumer = session.createConsumer(tempDest); // 設置消息監聽 consumer.setMessageListener(this); } /** * 中止 * @throws JMSException */ public void stop() throws JMSException { producer.close(); consumer.close(); session.close(); } /** * 請求 * @param request * @throws JMSException */ public void request(String request) throws JMSException { System.out.println("Request: " + request); // 建立文本消息 TextMessage textMessage = session.createTextMessage(); // 設置文本內容 textMessage.setText(request); // 設置回覆 textMessage.setJMSReplyTo(tempDest); // 獲取UUID String correlationId = UUID.randomUUID().toString(); // 設置JMS id textMessage.setJMSCorrelationID(correlationId); // 發送消息 this.producer.send(textMessage); } @Override public void onMessage(Message message) { try { System.out.println("Received response for: " + ((TextMessage)message).getText()); } catch (JMSException e) { e.printStackTrace(); } } public static void main(String[] args) throws JMSException, InterruptedException { Client client = new Client(); // 啓動 client.start(); int i = 0; while(i++ < 10) { client.request("REQUEST- " + i); } Thread.sleep(3000); client.stop(); } } 

IV. 測試

  • 啓動Server


     
    圖12.png
  • 啓動Client


     
    圖13.png

代碼下載

若是您以爲個人

做者:_凌浩雨 連接:https://www.jianshu.com/p/8b9bfe865e38 來源:簡書 簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。
相關文章
相關標籤/搜索