JAVA分佈式--ActiveMQ 消息中間件

  1. ActiveMQ

1). ActiveMQ
ActiveMQ是Apache所提供的一個開源的消息系統,完全採用Java來實現,因此,它能很好地支持J2EE提出的JMS(Java Message Service,即Java消息服務)規範。JMS是一組Java應用程序接口,它提供消息的創建、發送、讀取等一系列服務。JMS提供了一組公共應用程序接口和響應的語法,類似於Java數據庫的統一訪問接口JDBC,它是一種與廠商無關的API,使得Java程序能夠與不同廠商的消息組件很好地進行通信。
2). Java Message Service(JMS)
JMS支持兩種消息發送和接收模型。

一種稱爲P2P(Ponit to Point)模型,即採用點對點的方式發送消息。P2P模型是基於隊列的,消息生產者發送消息到隊列,消息消費者從隊列中接收消息,隊列的存在使得消息的異步傳輸稱爲可能,P2P模型在點對點的情況下進行消息傳遞時採用。
在這裏插入圖片描述
另一種稱爲Pub/Sub(Publish/Subscribe,即發佈-訂閱)模型,發佈-訂閱模型定義瞭如何向一個內容節點發布和訂閱消息,這個內容節點稱爲topic(主題)。主題可以認爲是消息傳遞的中介,消息發佈這將消息發佈到某個主題,而消息訂閱者則從主題訂閱消息。主題使得消息的訂閱者與消息的發佈者互相保持獨立,不需要進行接觸即可保證消息的傳遞,發佈-訂閱模型在消息的一對多廣播時採用。
在這裏插入圖片描述
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下載
在這裏插入圖片描述
bin (windows下面的bat(分32、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)
在這裏插入圖片描述
網絡端口(apache-activemq-5.15.3\conf)–默認爲8161
在這裏插入圖片描述
6). 啓動
\apache-activemq-5.15.3\bin\win64\目錄下雙擊activemq.bat文件,在瀏覽器中輸入http://localhost:8161/admin/, 用戶名和密碼輸入admin即可
在這裏插入圖片描述
7). 消息中間件(MOM:Message Orient middleware)
消息中間件有很多的用途和優點:

1 將數據從一個應用程序傳送到另一個應用程序,或者從軟件的一個模塊傳送到另外一個模塊;

負責建立網絡通信的通道,進行數據的可靠傳送。

保證數據不重發,不丟失

能夠實現跨平臺操作,能夠爲不同操作系統上的軟件集成技工數據傳送服務

8).什麼情況下使用ActiveMQ?

多個項目之間集成
(1) 跨平臺
(2) 多語言
(3) 多項目
降低系統間模塊的耦合度,解耦
(1) 軟件擴展性
系統前後端隔離
(1) 前後端隔離,屏蔽高安全區

2. ActiveMQ 示例
1). P2P 示例
I. 導包–activemq-all-5.15.3.jar
II. Producer

/**
 * 定義消息的生產者
 * @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. Consumer

/**
 * 定義消息的消費者
 * @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
在這裏插入圖片描述
ActiveMQ控制檯
在這裏插入圖片描述
再運行消費者Consumer
在這裏插入圖片描述
ActiveMQ控制檯
在這裏插入圖片描述
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. 實現思路
在這裏插入圖片描述
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
在這裏插入圖片描述
啓動Client
在這裏插入圖片描述

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