ActiveMQ是Apache所提供的一個開源的消息系統,徹底採用Java來實現,所以,它能很好地支持J2EE提出的JMS(Java Message Service,即Java消息服務)規範。JMS是一組Java應用程序接口,它提供消息的建立、發送、讀取等一系列服務。JMS提供了一組公共應用程序接口和響應的語法,相似於Java數據庫的統一訪問接口JDBC,它是一種與廠商無關的API,使得Java程序可以與不一樣廠商的消息組件很好地進行通訊。html
JMS支持兩種消息發送和接收模型。java
一種稱爲P2P(Ponit to Point)模型,即採用點對點的方式發送消息。P2P模型是基於隊列的,消息生產者發送消息到隊列,消息消費者從隊列中接收消息,隊列的存在使得消息的異步傳輸稱爲可能,P2P模型在點對點的狀況下進行消息傳遞時採用。linux
另外一種稱爲Pub/Sub(Publish/Subscribe,即發佈-訂閱)模型,發佈-訂閱模型定義瞭如何向一個內容節點發布和訂閱消息,這個內容節點稱爲topic(主題)。主題能夠認爲是消息傳遞的中介,消息發佈這將消息發佈到某個主題,而消息訂閱者則從主題訂閱消息。主題使得消息的訂閱者與消息的發佈者互相保持獨立,不須要進行接觸便可保證消息的傳遞,發佈-訂閱模型在消息的一對多廣播時採用。git
apache-activemq-5.15.3\conf
)apache-activemq-5.15.3\conf
)--默認爲8161\apache-activemq-5.15.3\bin\win64\
目錄下雙擊activemq.bat文件,在瀏覽器中輸入http://localhost:8161/admin/
, 用戶名和密碼輸入admin
便可
web
消息中間件有不少的用途和優勢:數據庫
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瀏覽器
ActiveMQ控制檯
再運行消費者Consumer
ActiveMQ控制檯
V. 消息類型
I. 實現思路
Client的Producer發出一個JMS message形式的request,request上附加了一些額外的屬性:
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
若是您以爲個人