RabbitMQ 实时消息推送到html页面

相关插件下载地址链接:https://pan.baidu.com/s/1PDV1gNsX2_zBOpElHJ4e0A

提取码:ajcn

 

复制这段内容后打开百度网盘手机App,操作更方便哦

一、安装 RabbitMQ 插件

安装方法见:http://note.youdao.com/noteshare?id=6f388514e547b07c56f8a10f0a8966cb&sub=1BF57BA3CE0A45548EB9B56960932257

 

二、启动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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值