我們在開發中經常會聽到ActiveMq、RabbitMQ、Kafka這些技術,其實他們都是消息中間件。 試想這樣一種場:當我們進行分佈式開發的時候,隨着程序功能的不斷增多,模塊也逐漸增多,模塊間的依賴關係也變得複雜起來。這種模塊之間的依賴也稱之爲耦合。而耦合越多,之後的維護工作就越困難。那麼如果改善系統模塊調用關係、減少模塊之間的耦合呢?這固然是必須的,消息中間件就是針對這種問題的一種解決方案
什麼是消息中間件
中間件我們可以理解爲是一個介於軟件和系統之間的程序,爲軟件提供基礎服務。消息中間件利用高效可靠的消息傳遞機制進行平臺無關的數據交流,並基於數據通信來進行分佈式系統的集成。通過提供消息傳遞和消息排隊模型,它可以在分佈式環境下擴展進程間的通信。對於消息中間件,常見的角色大致也就有Producer(生產者)、Consumer(消費者)。簡單來說消息中間件就是解決兩個服務間異步傳輸消息的軟件。
常見的消息中間件有:
(1)ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力強勁的開源消息總線。ActiveMQ 是一個完全支持JMS1.1和J2EE 1.4規範的 JMS Provider實現。
(2)RabbitMQ
AMQP協議的領導實現,支持多種場景。淘寶的MySQL集羣內部有使用它進行通訊,OpenStack開源雲平臺的通信組件,最先在金融行業得到運用。
(3)ZeroMQ
史上最快的消息隊列系統
(4)Kafka
Apache下的一個子項目 。特點:高吞吐,在一臺普通的服務器上既可以達到10W/s的吞吐速率;完全的分佈式系統。適合處理海量數據。
我們通過一張圖來直觀的體會一下消息中間件在整個系統中充當的角色
通過消息中間件activeMQ使運營商系統與搜索服務、頁面生成服務解除了耦合
JMS
什麼是JMS
JMS(Java Messaging Service)是Java平臺上有關面向消息中間件的技術規範,它便於消息系統中的Java應用程序進行消息交換,並且通過提供標準的產生、發送、接收消息的接口簡化企業應用的開發。
JMS本身只定義了一系列的接口規範,是一種與廠商無關的 API,用來訪問消息收發系統。它類似於 JDBC(java Database Connectivity):這裏,JDBC 是可以用來訪問許多不同關係數據庫的 API,而 JMS 則提供同樣與廠商無關的訪問方法,以訪問消息收發服務。許多廠商目前都支持 JMS,包括 IBM 的 MQSeries、BEA的 Weblogic JMS service和 Progress 的 SonicMQ,這只是幾個例子。 JMS 使您能夠通過消息收發服務(有時稱爲消息中介程序或路由器)從一個 JMS 客戶機向另一個 JML 客戶機發送消息。消息是 JMS 中的一種類型對象,由兩部分組成:報頭和消息主體。報頭由路由信息以及有關該消息的元數據組成。消息主體則攜帶着應用程序的數據或有效負載。
JMS 定義了五種不同的消息正文格式,以及調用的消息類型,允許你發送並接收以一些不同形式的數據,提供現有消息格式的一些級別的兼容性。
- TextMessage–一個字符串對象
- MapMessage–一套名稱-值對
- ObjectMessage–一個序列化的 Java 對象
- BytesMessage–一個字節的數據流
- StreamMessage – Java 原始值的數據流
JMS消息傳遞類型
對於消息的傳遞有兩種類型:
一種是點對點的,即一個生產者和一個消費者一一對應;
如果有多個消費者接收的話,只有一個能接收到該傳遞類型的消息
另一種是發佈/ 訂閱模式,即一個生產者產生消息並進行發送後,可以由多個消費者進行接收。
ActiveMQ
下載與安裝
1.官方網站下載:http://activemq.apache.org/
2.linux下安裝
(1)將apache-activemq-5.12.0-bin.tar.gz 上傳至服務器
(2)解壓此文件
tar zxvf apache-activemq-5.12.0-bin.tar.gz
(3)爲apache-activemq-5.12.0目錄賦權
chmod 777 apache-activemq-5.12.0
(4)進入apache-activemq-5.12.0/bin目錄
cd apache-activemq-5.12.0/bin
(5)賦與執行權限
chmod 755 activemq
(6)啓動
./activemq start
啓動完成後,訪問 http://服務器ip地址:8161,如果可以正常訪問,則已經啓動成功,如果無法訪問,首先檢查服務器8161端口是否開啓。如果已開啓依然不能訪問,可以參考https://blog.csdn.net/WB1224678/article/details/100097553這篇博客
入門Demo
點對點模式
1.創建maven工程引入ActiveMQ依賴
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-client</artifactId>
<version>5.13.4</version>
</dependency>
2.編寫消息生產者
public class QueueProducer {
public static void main(String[] args) throws JMSException {
//1.創建連接工廠
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://140.143.21.45:61616");
//2.獲取連接
Connection connection = factory.createConnection();
//3.啓動連接
connection.start();
//4.獲取Session(參數是1否啓動事務,參數2消息確認模式)
/*AUTO_ACKNOWLEDGE = 1 自動確認
CLIENT_ACKNOWLEDGE = 2 客戶端手動確認
DUPS_OK_ACKNOWLEDGE = 3 自動批量確認
SESSION_TRANSACTED = 0 事務提交併確認*/
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.創建隊列對象
Queue queue = session.createQueue("test-queue");
//6.創建消息生產者
MessageProducer producer = session.createProducer(queue);
//7.創建消息
TextMessage message = session.createTextMessage("Hello ActiveMQ");
//8.發送消息
producer.send(message);
//9.關閉資源
producer.close();
session.close();
connection.close();
}
}
3.編寫消息消費者
public class QueueConsumer {
public static void main(String[] args) throws JMSException, IOException {
//1.創建連接工廠
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://140.143.21.45:61616");
//2.創建連接
Connection connection = factory.createConnection();
//3.開啓連接
connection.start();
//4.獲取Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.創建消息隊列對象
Queue queue = session.createQueue("test-queue");
//6.創建消息消費者
MessageConsumer consumer = session.createConsumer(queue);
//7.監聽消息
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
//8.等待鍵盤輸入,因爲是個入門demo,寫這句話是爲了防止還沒有監聽到信息,資源就都關閉了
System.in.read();
//9.關閉資源
consumer.close();
session.close();
connection.close();
}
}
發佈/訂閱模式
消息生產者
//1.創建連接工廠
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://192.168.25.135:61616");
//2.獲取連接
Connection connection = connectionFactory.createConnection();
//3.啓動連接
connection.start();
//4.獲取session (參數1:是否啓動事務,參數2:消息確認模式)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.創建主題對象
Topic topic = session.createTopic("test-topic");
//6.創建消息生產者
MessageProducer producer = session.createProducer(topic);
//7.創建消息
TextMessage textMessage = session.createTextMessage("歡迎來到神奇的品優購世界");
//8.發送消息
producer.send(textMessage);
//9.關閉資源
producer.close();
session.close();
connection.close();
消息消費者
//1.創建連接工廠
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://192.168.25.135:61616");
//2.獲取連接
Connection connection = connectionFactory.createConnection();
//3.啓動連接
connection.start();
//4.獲取session (參數1:是否啓動事務,參數2:消息確認模式)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.創建主題對象
//Queue queue = session.createQueue("test-queue");
Topic topic = session.createTopic("test-topic");
//6.創建消息消費
MessageConsumer consumer = session.createConsumer(topic);
//7.監聽消息
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage=(TextMessage)message;
try {
System.out.println("接收到消息:"+textMessage.getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//8.等待鍵盤輸入
System.in.read();
//9.關閉資源
consumer.close();
session.close();
connection.close();
Spring整合Demo
點對點模式
1.消息提供者
(1)創建工程springjms_producer,在POM文件中引入SpringJms 、activeMQ以及單元測試相關依賴
(2)在src/main/resources下創建spring配置文件applicationContext-jms-producer.xml
<context:component-scan base-package="cn.gzc.demo"></context:component-scan>
<!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://192.168.25.135:61616"/>
</bean>
<!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
<property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>
<!-- Spring提供的JMS工具類,它可以進行消息發送、接收等 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<!-- 這個connectionFactory對應的是我們定義的Spring提供的那個ConnectionFactory對象 -->
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<!--這個是隊列目的地,點對點的 文本信息-->
<bean id="queueTextDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="queue_text"/>
</bean>
(3)在cn.gzc.demo包下創建消息生產者類
@Component
public class QueueProducer {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Destination queueTextDestination;
/**
* 發送文本消息
* @param text
*/
public void sendTextMessage(final String text){
jmsTemplate.send(queueTextDestination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(text);
}
});
}
}
(4)單元測試
在src/test/java創建測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-producer.xml")
public class TestQueue {
@Autowired
private QueueProducer queueProducer;
@Test
public void testSend(){
queueProducer.sendTextMessage("SpringJms-點對點");
}
}
2.消息消費者
(1)創建工程springjms_consumer,在POM文件中引入依賴 (同上一個工程)
(2)創建配置文件 applicationContext-jms-consumer-queue.xml
<!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://192.168.25.135:61616"/>
</bean>
<!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
<property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>
<!--這個是隊列目的地,點對點的 文本信息-->
<bean id="queueTextDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="queue_text"/>
</bean>
<!-- 我的監聽類 -->
<bean id="myMessageListener" class="cn.gzc.demo.MyMessageListener"></bean>
<!-- 消息監聽容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="queueTextDestination" />
<property name="messageListener" ref="myMessageListener" />
</bean>
(3)編寫監聽類
public class MyMessageListener implements MessageListener {
public void onMessage(Message message) {
TextMessage textMessage=(TextMessage)message;
try {
System.out.println("接收到消息:"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
(4)創建測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-consumer-queue.xml")
public class TestQueue {
@Test
public void testQueue(){
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
發佈/訂閱模式
1.消息生產者
(1)在工程springjms_producer的applicationContext-jms-producer.xml增加配置
<!--這個是訂閱模式 文本信息-->
<bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="topic_text"/>
</bean>
(2)創建生產者類
@Component
public class TopicProducer {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Destination topicTextDestination;
/**
* 發送文本消息
* @param text
*/
public void sendTextMessage(final String text){
jmsTemplate.send(topicTextDestination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(text);
}
});
}
}
(3)編寫測試類
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.gzc.demo.TopicProducer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-activemq-producer.xml")
public class TestTopic {
@Autowired
private TopicProducer topicProducer;
@Test
public void sendTextQueue(){
topicProducer.sendTextMessage();
}
}
2.消息消費者
(1)在activemq-spring-consumer工程中創建配置文件applicationContext-jms-consumer-topic.xml
<!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://192.168.25.135:61616"/>
</bean>
<!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
<property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>
<!--這個是隊列目的地,點對點的 文本信息-->
<bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="topic_text"/>
</bean>
<!-- 我的監聽類 -->
<bean id="myMessageListener" class="cn.gzc.demo.MyMessageListener"></bean>
<!-- 消息監聽容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="topicTextDestination" />
<property name="messageListener" ref="myMessageListener" />
</bean>
(2)編寫測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-consumer-topic.xml")
public class TestTopic {
@Test
public void testTopic(){
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
測試:同時運行多個消費者工程,在運行生產者工程,查看三個消費者工程的控制檯輸出。