消息中間件用於降低各個項目模塊的耦合,適用於不需要等待返回消息才能進入下一個業務環節的模塊,以及實時要求性不高的業務模塊。
一、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消息傳遞類型
對於消息的傳遞有兩種類型:
一種是點對點的,即一個生產者和一個消費者一一對應;其實是只能由一個消費者消費消息。
另一種是發布/ 訂閱模式,即一個生產者產生消息並進行發送后,可以由多個消費者進行接收。由於采取訂閱/廣播的形式,錯過了廣播就會接受不到消息。
二、消息中間件
消息中間件利用高效可靠的消息傳遞機制進行平台無關的數據交流,並基於數據通信來進行分布式系統的集成。通過提供消息傳遞和消息排隊模型,它可以在分布式環境下擴展進程間的通信。對於消息中間件,常見的角色大致也就有Producer(生產者)、Consumer(消費者)。
常見的消息中間件產品:
(1)ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力強勁的開源消息總線。ActiveMQ 是一個完全支持JMS1.1和J2EE 1.4規范的 JMS Provider實現。我們在本次課程中介紹 ActiveMQ的使用。
(2)RabbitMQ
AMQP協議的領導實現,支持多種場景。淘寶的MySQL集群內部有使用它進行通訊,OpenStack開源雲平台的通信組件,最先在金融行業得到運用。
(3)ZeroMQ
史上最快的消息隊列系統
(4)Kafka
Apache下的一個子項目 。特點:高吞吐,在一台普通的服務器上既可以達到10W/s的吞吐速率;完全的分布式系統。適合處理海量數據。
三、ActiveMQ簡介
官方網站下載:http://activemq.apache.org/
無論是windows還是linux都是下載解壓即用的,類似與zookeeper,不同的是不需要什么配置。后台管理賬戶和密碼默認都是admin
bin目錄下 activemq.bat 或者 activemq.sh 啟動即可。
四、spring整合JMS
①:點對點模式
點對點的模式主要建立在一個隊列上面,當連接一個列隊的時候,發送端不需要知道接收端是否正在接收,可以直接向ActiveMQ發送消息,發送的消息,將會先進入隊列中,如果有接收端在監聽,則會發向接收端,如果沒有接收端接收,則會保存在activemq服務器,直到接收端接收消息,點對點的消息模式可以有多個發送端,多個接收端,但是一條消息,只會被一個接收端給接收到,哪個接收端先連上ActiveMQ,則會先接收到,而后來的接收端則接收不到那條消息。
消息生產者
(1)創建工程,在POM文件中引入SpringJms 、activeMQ相關依賴
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-client</artifactId>
<version>5.13.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
(2)在src/main/resources下創建spring配置文件applicationContext-jms-producer.xml
<context:component-scanbase-package="cn.itcast.demo"></context:component-scan> <!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供--> <beanid="targetConnectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory"> <propertyname="brokerURL"value="tcp://192.168.25.135:61616"/> </bean> <!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory --> <beanid="connectionFactory"class="org.springframework.jms.connection.SingleConnectionFactory"> <!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory --> <propertyname="targetConnectionFactory"ref="targetConnectionFactory"/> </bean> <!-- Spring提供的JMS工具類,它可以進行消息發送、接收等 --> <beanid="jmsTemplate"class="org.springframework.jms.core.JmsTemplate"> <!-- 這個connectionFactory對應的是我們定義的Spring提供的那個ConnectionFactory對象 --> <propertyname="connectionFactory"ref="connectionFactory"/> </bean> <!--這個是隊列目的地,點對點的 文本信息--> <beanid="queueTextDestination"class="org.apache.activemq.command.ActiveMQQueue"> <constructor-argvalue="queue_text"/> </bean>
(3)在cn.itcast.demo包下創建消息生產者類
@Component publicclass QueueProducer { @Autowired private JmsTemplate jmsTemplate; @Autowired private Destination queueTextDestination; /** * 發送文本消息 * @param text */ publicvoid sendTextMessage(final String text){ jmsTemplate.send(queueTextDestination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { returnsession.createTextMessage(text); } }); } }
4)單元測試 在src/test/java創建測試類
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext-jms-producer.xml") publicclass TestQueue { @Autowired private QueueProducer queueProducer; @Test publicvoid testSend(){ queueProducer.sendTextMessage("SpringJms-點對點"); } }
消息消費者
(1)創建工程springjms_consumer,在POM文件中引入依賴 (同上一個工程)
(2)創建配置文件 applicationContext-jms-consumer-queue.xml
<!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供--> <beanid="targetConnectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory"> <propertyname="brokerURL"value="tcp://192.168.25.135:61616"/> </bean> <!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory --> <beanid="connectionFactory"class="org.springframework.jms.connection.SingleConnectionFactory"> <!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory --> <propertyname="targetConnectionFactory"ref="targetConnectionFactory"/> </bean> <!--這個是隊列目的地,點對點的 文本信息--> <beanid="queueTextDestination"class="org.apache.activemq.command.ActiveMQQueue"> <constructor-argvalue="queue_text"/> </bean> <!-- 我的監聽類 --> <beanid="myMessageListener"class="cn.itcast.demo.MyMessageListener"></bean> <!-- 消息監聽容器 --> <beanclass="org.springframework.jms.listener.DefaultMessageListenerContainer"> <propertyname="connectionFactory"ref="connectionFactory"/> <propertyname="destination"ref="queueTextDestination"/> <propertyname="messageListener"ref="myMessageListener"/> </bean>
(3)編寫監聽類
publicclass MyMessageListener implements MessageListener { publicvoid 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") publicclass TestQueue { @Test publicvoid testQueue(){ try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }
②:發布/訂閱模式
消息生產者
(1)在工程springjms_producer的applicationContext-jms-producer.xml增加配置。同上需要引入ActiveMQ和JMS額依賴
<!--這個是訂閱模式 文本信息--> <beanid="topicTextDestination"class="org.apache.activemq.command.ActiveMQTopic"> <constructor-argvalue="topic_text"/> </bean>
(2)創建生產者類
@Component publicclass TopicProducer { @Autowired private JmsTemplate jmsTemplate; @Autowired private Destination topicTextDestination; /** * 發送文本消息 * @param text */ publicvoid sendTextMessage(final String text){ jmsTemplate.send(topicTextDestination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { returnsession.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.itcast.demo.TopicProducer; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext-activemq-producer.xml") publicclass TestTopic { @Autowired private TopicProducer topicProducer; @Test publicvoid sendTextQueue(){ topicProducer.sendTextMessage(); } }
消息消費者
(1)在activemq-spring-consumer工程中創建配置文件applicationContext-jms-consumer-topic.xml。同上需要引入ActiveMQ和JMS額依賴
<!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供--> <beanid="targetConnectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory"> <propertyname="brokerURL"value="tcp://192.168.25.135:61616"/> </bean> <!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory --> <beanid="connectionFactory"class="org.springframework.jms.connection.SingleConnectionFactory"> <!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory --> <propertyname="targetConnectionFactory"ref="targetConnectionFactory"/> </bean> <!--這個是隊列目的地,點對點的 文本信息--> <bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic"> <constructor-arg value="topic_text"/> </bean> <!-- 我的監聽類 --> <beanid="myMessageListener"class="cn.itcast.demo.MyMessageListener"></bean> <!-- 消息監聽容器 --> <beanclass="org.springframework.jms.listener.DefaultMessageListenerContainer"> <propertyname="connectionFactory"ref="connectionFactory"/> <propertyname="destination"ref="topicTextDestination"/> <propertyname="messageListener"ref="myMessageListener"/> </bean>
(2)編寫測試類
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext-jms-consumer-topic.xml") publicclass TestTopic { @Test publicvoidtestTopic(){ try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }
五、springboot整合JMS
1、使用內嵌服務
(1)在pom.xml中引入ActiveMQ起步依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
(2)創建消息生產者
/** * 消息生產者 * @author Administrator */ @RestController publicclass QueueController { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @RequestMapping("/send") publicvoid send(String text){ jmsMessagingTemplate.convertAndSend("itcast", text); } }
(3)創建消息消費者
@Component publicclass Consumer { @JmsListener(destination="itcast") publicvoid readMessage(String text){ System.out.println("接收到消息:"+text); } }
測試:啟動服務后,在瀏覽器執行
http://localhost:8080/send.do?text=aaaaa
即可看到控制台輸出消息提示。Spring Boot內置了ActiveMQ的服務,所以我們不用單獨啟動也可以執行應用程序。
2、使用外部服務
在src/main/resources下的application.properties增加配置, 指定ActiveMQ的地址
spring.activemq.broker-url=tcp://192.168.25.135:61616
(1)修改QueueController.java,發送map消息
@RequestMapping("/sendmap") publicvoid sendMap(){ Mapmap=new HashMap<>(); map.put("mobile", "13900001111"); map.put("content", "恭喜獲得10元代金券"); jmsMessagingTemplate.convertAndSend("itcast_map",map); }
(2)修改Consumer.java
@JmsListener(destination="itcast_map") publicvoid readMap(Mapmap){ System.out.println(map); }