本文部分內容參考自: https://www.cnblogs.com/yufeng218/p/11509486.html
一、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模型在點對點的情況下進行消息傳遞時採用。
圖1.png
-
另一種稱爲Pub/Sub(Publish/Subscribe,即發佈-訂閱)模型,發佈-訂閱模型定義瞭如何向一個內容節點發布和訂閱消息,這個內容節點稱爲topic(主題)。主題可以認爲是消息傳遞的中介,消息發佈這將消息發佈到某個主題,而消息訂閱者則從主題訂閱消息。主題使得消息的訂閱者與消息的發佈者互相保持獨立,不需要進行接觸即可保證消息的傳遞,發佈-訂閱模型在消息的一對多廣播時採用。
圖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創建的
二、Windows安裝 ActiveMq
1、下載地址:http://activemq.apache.org/download-archives.html ,本文用的是windows版的5.15.10版本,下載下來是壓縮包。apache-activemq-5.15.10-bin.tar.gz
2、將壓縮包解壓一個到目錄下,CMD進入到解壓目錄下的bin目錄下,執行 activemq.bat start 啓動。 如果能成功訪問 http://localhost:8161/admin(用戶名和密碼默認爲admin),則啓動成功。
三、SpringBoot 集成 ActiveMQ
1. 創建一個springboot項目,添加依賴
<!--ActiveMq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<!-- <version>2.1.0.RELEASE</version> -->
</dependency>
<!--消息隊列連接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<!-- <version>5.15.7</version> -->
</dependency>
2、application.yml文件的配置
server:
port: 8090
spring:
activemq:
broker-url: tcp://192.168.111.200:61616
user: admin
password: admin
close-timeout: 15s # 在考慮結束之前等待的時間
in-memory: true # 默認代理URL是否應該在內存中。如果指定了顯式代理,則忽略此值。
non-blocking-redelivery: false # 是否在回滾回滾消息之前停止消息傳遞。這意味着當啓用此命令時,消息順序不會被保留。
send-timeout: 0 # 等待消息發送響應的時間。設置爲0等待永遠。
queue-name: active.queue
topic-name: active.topic.name.model
# packages:
# trust-all: true #不配置此項,會報錯
pool:
enabled: true
max-connections: 10 #連接池最大連接數
idle-timeout: 30000 #空閒的連接過期時間,默認爲30秒
# jms:
# pub-sub-domain: true #默認情況下activemq提供的是queue模式,若要使用topic模式需要配置此項
#其他配置項:
# 是否信任所有包
#spring.activemq.packages.trust-all=
# 要信任的特定包的逗號分隔列表(當不信任所有包時)
#spring.activemq.packages.trusted=
# 當連接請求和池滿時是否阻塞。設置false會拋“JMSException異常”。
#spring.activemq.pool.block-if-full=true
# 如果池仍然滿,則在拋出異常前阻塞時間。
#spring.activemq.pool.block-if-full-timeout=-1ms
# 是否在啓動時創建連接。可以在啓動時用於加熱池。
#spring.activemq.pool.create-connection-on-startup=true
# 是否用Pooledconnectionfactory代替普通的ConnectionFactory。
#spring.activemq.pool.enabled=false
# 連接過期超時。
#spring.activemq.pool.expiry-timeout=0ms
# 連接空閒超時
#spring.activemq.pool.idle-timeout=30s
# 連接池最大連接數
#spring.activemq.pool.max-connections=1
# 每個連接的有效會話的最大數目。
#spring.activemq.pool.maximum-active-session-per-connection=500
# 當有"JMSException"時嘗試重新連接
#spring.activemq.pool.reconnect-on-exception=true
# 在空閒連接清除線程之間運行的時間。當爲負數時,沒有空閒連接驅逐線程運行。
#spring.activemq.pool.time-between-expiration-check=-1ms
# 是否只使用一個MessageProducer
#spring.activemq.pool.use-anonymous-producers=true
3、啓動類增加 @EnableJms 註解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.annotation.EnableJms;
@SpringBootApplication
@EnableJms //啓動消息隊列
public class SpringbootActivemqApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootActivemqApplication.class, args);
}
}
4、初始化和配置 ActiveMQ 的連接
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
@Configuration
publicclass BeanConfig
{
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
@Value("${spring.activemq.user}")
private String username;
@Value("${spring.activemq.topic-name}")
private String password;
@Value("${spring.activemq.queue-name}")
private String queueName;
@Value("${spring.activemq.topic-name}")
private String topicName;
@Bean(name = "queue")
public Queue queue() {
return new ActiveMQQueue(queueName);
}
//如果有多個queue主題,則繼續增加@Bean, @Bean內的name可省略,省略後name爲方法名("queue2"),
//注意: 後續@Autowired註解“public Queue queue2;”的變量名爲此處的name("queue2");
//隊列名稱爲"queueName2", 後續的隊列消費時destination要和此隊列名稱一致。
@Bean(name = "queue2")
public Queue queue2() {
return new ActiveMQQueue("queueName2");
}
//其他的queue主題定義
//...
@Bean(name = "topic")
public Topic topic() {
return new ActiveMQTopic(topicName);
}
@Bean(name = "topic2")
public Topic topic2() {
return new ActiveMQTopic("topicName2");
}
//其他的topic主題定義
//...
@Bean
public ConnectionFactory connectionFactory(){
return new ActiveMQConnectionFactory(username, password, brokerUrl);
}
@Bean
public JmsMessagingTemplate jmsMessageTemplate(){
return new JmsMessagingTemplate(connectionFactory());
}
// 在Queue模式中,對消息的監聽需要對containerFactory進行配置
@Bean("queueListener")
public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(false);
return factory;
}
//在Topic模式中,對消息的監聽需要對containerFactory進行配置
@Bean("topicListener")
public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(true);
return factory;
}
}
5、生產者(queue 和 topic)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
@RestController
public class ProducerController
{
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Autowired
private Queue queue2;
//更多的Queue...
@Autowired
private Topic topic;
//更多的topic...
@PostMapping("/queue/test")
public String sendQueue(@RequestBody String str) {
this.sendMessage(this.queue, str);
return "success";
}
@PostMapping("/queue2/test")
public String sendQueue(@RequestBody String str) {
this.sendMessage(this.queue2, str);
return "queue2 success";
}
@PostMapping("/topic/test")
public String sendTopic(@RequestBody String str) {
this.sendMessage(this.topic, str);
return "success";
}
// 發送消息,destination是發送到的隊列,message是待發送的消息
private void sendMessage(Destination destination, final String message){
jmsMessagingTemplate.convertAndSend(destination, message);
}
}
6、Queue模式的消費者
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class QueueConsumerListener
{
//queue模式的消費者
@JmsListener(destination="${spring.activemq.queue-name}", containerFactory="queueListener")
public void readActiveQueue(String message) {
System.out.println("queue接受到:" + message);
}
//queue2模式的消費者, destination爲queue主題,和ActiveMQBeanConfig定義中的@Bean中的"new ActiveMQQueue("queueName2");"的參數一致
@JmsListener(destination="queueName2", containerFactory="queueListener")
public void readActiveQueue(String message) {
System.out.println("queue2接受到:" + message);
}
//更多的queue模式的消費者。。。
}
7、topic模式的消費者
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class TopicConsumerListener
{
//topic模式的消費者
@JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
public void readActiveQueue(String message) {
System.out.println("topic接受到:" + message);
}
//其他的topic模式的消費者。。。
}
8、測試(使用Postman發消息)
(1) POST: http://localhost:8090/queue/test 消息體:{"aaa" : "queue"}
控制檯打印:queue接受到:{"aaa" : "queue"}
(2) POST: http://localhost:8090/queue2/test 消息體:{"bbb" : "queue2"}
控制檯打印:queue2接受到:{"bbb" : "queue2"}
(3) POST: http://localhost:8090/topic/test 消息體:{"aaa" : "topic"}
控制檯打印:topic接受到:{"aaa" : "topic"}
topic模式有普通訂閱和持久化訂閱
普通訂閱:在消費者啓動之前發送過來的消息,消費者啓動之後不會去消費;
持久化訂閱: 在消費者啓動之前發送過來的消息,消費者啓動之後會去消費;
四、前端VUE使用Stompjs接收ActiveMQ消息
引用原文鏈接:https://blog.csdn.net/yuandongy/article/details/103261001
1 創建vue項目
vue init webpack demo
2 進入demo文件夾,安裝stompjs,net
cd demo
npm install stompjs
npm install net
3 在config下添加linkparam.js
export const MQ_SERVICE = 'ws://192.168.111.200:61614/stomp' // mq服務地址
export const MQ_USERNAME = 'admin' // mq連接用戶名
export const MQ_PASSWORD = 'admin' //mq連接密碼
4 在src/components下添加sock.vue文件
<template>
<div>
socket is loading...
</div>
</template>
<script>
import Stomp from 'stompjs'
import { MQ_SERVICE, MQ_USERNAME, MQ_PASSWORD } from '../../config/linkparam.js'
export default {
name: 'entry',
data () {
return {
client: Stomp.client(MQ_SERVICE)
}
},
created () {
this.connect()
},
methods: {
onConnected: function (frame) {
console.log('Connected: ' + frame)
var queue= 'active.queue'
this.client.subscribe(queue, this.responseCallback, this.onFailed)
var topic = 'active.topic.name.model'
this.client.subscribe(topic, this.responseCallback, this.onFailed)
},
onFailed: function (frame) {
console.log('Failed: ' + frame)
},
responseCallback: function (frame) {
console.log('responseCallback msg=>' + frame.body)
console.log('------')
},
connect: function () {
var headers = {
'login': MQ_USERNAME,
'passcode': MQ_PASSWORD
}
this.client.connect(headers, this.onConnected, this.onFailed)
}
}
}
</script>
5 修改src/App.vue
<template>
<div id="app">
<sock/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
import sock from './components/sock'
export default {
name: 'App',
components: {
sock
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
6 運行vue
npm run dev
7 測試
進入ActiveMQ控制檯,如下,
設置好後,點擊“send”。
或使用Postman發消息:POST: http://localhost:8090/queue/test 消息體:{"aaa" : "queue"}
F12進入調試模式,看打印結果:
...
responseCallback msg=>{"aaa" : "queue"}
------
至此,全部完成