相关插件下载地址链接:https://pan.baidu.com/s/1PDV1gNsX2_zBOpElHJ4e0A
提取码:ajcn
复制这段内容后打开百度网盘手机App,操作更方便哦
一、安装 RabbitMQ 插件
二、启动RabbitMQ和stomp服务
***cmd命令窗口
1、启动或关闭RabbitMQ服务命令
启动(默认端口15672):net start RabbitMQ
关闭:net stop RabbitMQ
2、启动stomp服务命令
进入mq安装目录C:\Program Files\RabbitMQ Server\rabbitmq_server-3.6.5\sbin\
启动(默认端口15674):rabbitmq-plugins enable rabbitmq_web_stomp
关闭:rabbitmq-plugins disable rabbitmq_web_stomp
三、后台代码
(1)maven项目,pom.xml引入包:
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
(2)后台服务端发送信息方法
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("rabbitmq", "fanout");
String routingKey = "rabbitmq_routingkey";
String message = “hello world!”;
channel.basicPublish("rabbitmq", routingKey,null, message.getBytes());
System.out.println("[x] Sent Message:"+message);
channel.close();
connection.close();
四、前端代码
<html>
<head>
<script src="./lib/jquery-1.9.1.min.js"></script>
<script src="./lib/sockjs.min.js"></script>
<script src="./lib/stomp.js"></script>
<title>RabbitMQ Web STOMP Examples : Echo Server</title>
<meta charset="UTF-8">
</head>
<body lang="en">
<hr/>
<hr/>
<script>
// 初始化 ws 对象
if (location.search == '?ws') {
var ws = new WebSocket('ws://localhost:15672/ws');
} else {
var ws = new SockJS('http://localhost:15674/stomp');
}
// 获得Stomp client对象
var client = Stomp.over(ws);
// SockJS does not support heart-beat: disable heart-beats
client.heartbeat.outgoing = 0;
client.heartbeat.incoming = 0;
//client.debug = pipe('#second');
// 定义连接成功回调函数
var on_connect = function(x) {
//data.body是接收到的数据
client.subscribe("/exchange/rabbitmq/rabbitmq_routingkey", function(data) {
var msg = data.body;
alert("收到数据:" + msg);
});
};
// 定义错误时回调函数
var on_error = function() {
console.log('error');
};
// 连接RabbitMQ
client.connect('guest', 'guest', on_connect, on_error, '/');
console.log(">>>连接上http://localhost:15672");
</script>
</body>
</html