ActiveMQ使用(一):在JavaScript中使用stomp.js

news/2024/3/28 19:53:31/文章来源:https://blog.csdn.net/ice_bear221/article/details/130142203

ActiveMQ使用(一):在JavaScript中使用stomp.js

1. 环境准备

  1. jQuery-1.10
    下载地址:https://www.jsdelivr.com/package/npm/jquery-1.10.2?tab=files
  2. stomp.js 2.3.3:
    下载地址:https://www.jsdelivr.com/package/npm/stompjs
    在这里插入图片描述

2. 相关代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><div class="connect-input-box"><label for="host">host:</label><input type="text" name="host" placeholder="input host" value="127.0.0.1"><br><label for="port">port:</label><input type="text" name="port" placeholder="input port" value="61614"><br><label for="clientId">client id:</label><input type="text" name="clientId" placeholder="input client id"><br><label for="userId">user id:</label><input type="text" name="userId" placeholder="input user id" value="user"><br><label for="password">password:</label><input type="text" name="password" placeholder="input password" value="pass"><br><label for="destination">destination:</label><input type="text" name="destination" placeholder="input destination" value="world"><br><button id="connect" type="submit">connect</button><button id="disconnect" type="submit">disconnect</button></div><div class="log-box"><p id="log-show"></p></div><div class="send-message-box"><label for="topic">topic:</label><input type="text" name="topic"><br><label for="queue">queue:</label><input type="text" name="queue"><br><input type="text" name="message"><br><button id="send">send</button></div><div class="subscribe-box"><label for="subscribe-topic">subscribe-topic:</label><input type="text" name="subscribe-topic"><button id="subscribe">subscribe</button></div><div class="unsubscribe-box"><label for="unsubscribe-topic"></label><input type="text" name="unsubscribe-topic"><button id="unsubscribe">unsubscribe</button></div><script src="plugins/jquery-1.10.1.js"></script><script src="plugins/stomp.js"></script><script type="module">$(() => {console.log('mqtt: ', Stomp)$('input[name="clientId"]').val("example-" + Math.floor(Math.random() * 10000))if (!window.WebSocket) {console.log('不支持WebSocket')} else {}})var client, destination$('#connect').click(() => {var host = $('input[name="host"]').val()var port = $('input[name="port"]').val()var clientId = $('input[name="clientId"]').val()var user = $('input[name="userId"]').val()var password = $('input[name="password"]').val()destination = $('input[name="destination"]').val()console.log(host)// 创建一个client 实例let url = 'ws://' + host + ':' + port + '/stomp'client = Stomp.client(url)console.log(client)let headers = {login: user,passcode: password,'client-id': clientId}client.connect(headers, () => {console.log('connect success')client.subscribe(destination, (message) => {if (message.body) {console.log('get body ' + message.body)} else {console.log('got empty message')}})}, () => {console.log('connect failed')})})// 断开连接$('#disconnect').click(() => {console.log('disconnect');client.disconnect(() => {console.log('disconnect')})})// 发送消息$('#send').click(() => {console.log('send')let topic = $('input[name="topic"]').val()let payload = $('input[name="message"]').val()let headers = {}client.send(topic, headers, payload)})var subscribeId = null// 订阅主题$('#subscribe').click(() => {console.log('subscribe')let topic = $('input[name="subscribe-topic"]').val()subscribeId = client.subscribe(topic, (message) => {if (message.body) {console.log('message body: ' + message.body)} else {console.log('empty message')}}, {id: '123123'})})// 取消订阅主题$('#unsubscribe').click(() => {console.log('unsubscribe')console.log(subscribeId);client.unsubscribe(subscribeId.id)})</script>
</body>
</html>

3. 结果展示

在这里插入图片描述

3.1 连接

在这里插入图片描述

3.2 订阅

在这里插入图片描述

3.3 发送消息

在这里插入图片描述

注意:默认发送点对点消息, 发送主题消息需要添加前缀/topic

在这里插入图片描述

3.4 取消订阅

在这里插入图片描述

3.5 断开连接

在这里插入图片描述

4. 相关参考

前端 Websocket + Stomp.js 的使用

stompjs的所有方法的使用

activemq BytesMessage || TextMessage

STOMP Over WebSocket

5. 注意

SprintBoot项目中集成ActiveMQ后,接收到的数据为字节数组
一种解决方式为:

@JmsListener(destination = "test_producer", containerFactory = "topicListenerContainer")public void receiveTestProducer(Message message) throws JMSException {String msg = StringUtils.activeMQMessageParse(message);System.out.println("收到测试生产者的消息: " + msg);}public class StringUtils {/*** 将字符串进行分割并获得字节数组* @param str 待处理字符串* @param split 分割字符串* @return 字节数组*/public static byte[] stringToBytes(String str, String split) {String[] strArr = str.split(split);byte[] byteArr = new byte[strArr.length];for (int i = 0; i < strArr.length; i++) {byteArr[i] = (byte) Integer.parseInt(strArr[i]);}return byteArr;}/*** 根据字节数组获取指定字符集的字符串* @param byteArr 字节数组* @param charset 编码字符集* @return 处理后的字符串*/public static String bytesToString(byte[] byteArr, Charset charset) {return new String(byteArr, charset);}/*** 将字符串根据分隔符转成字节数组,然后转成指定字符集的字符串* @param str 待处理字符串* @param split 分割字符串* @param charset 指定字符集* @return 处理后的字符串*/public static String stringToString(String str, String split, Charset charset) {return bytesToString(stringToBytes(str, split), charset);}/*** 将ActiveMQ接收到的消息转换为UTF-8字符串* @param message* @return*/public static String activeMQMessageParse(Message message) {String str = null;if (message instanceof ActiveMQTextMessage) {ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;try {str = textMessage.getText().toString();} catch (JMSException e) {e.printStackTrace();}
//            System.out.println("text : " + textMessage.getText());} else if (message instanceof ActiveMQBytesMessage) {ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage) message;byte[] byteArr = new byte[0];try {byteArr = new byte[(int) bytesMessage.getBodyLength()];int flag = bytesMessage.readBytes(byteArr);str = bytesToString(byteArr, StandardCharsets.UTF_8);
//                System.out.println("bytes : " + flag + " : " + str);} catch (JMSException e) {e.printStackTrace();}}return str;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_286492.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ABAP 创建、修改、删除内部交货单(VL31N/VL32N)

一、干货 VL31N创建的BAPI&#xff1a; 1.GN_DELIVERY_CREATE 通用交货单使用的bapi&#xff0c;推荐使用 2.BAPI_DELIVERYPROCESSING_EXEC 简单&#xff0c;但是字段比较少 3.BBP_INB_DELIVERY_CREATE 听说有bug&#xff0c;我就没有使用这个了 VL32N修改/删除BAPI: BAPI_INB…

从此告别PPT制作的烦恼:ChatGPT和MindShow帮你快速完成

目录前言一、chatGPT&MindShow简介二、chatGPT&MindShow搭配生成PPT2-1、注意事项2-2、生成PPT的步骤2-3、使用chatGPT进行探索2-4、内容生成2-5、PPT制作三、碎碎念总结前言 随着科技的不断发展&#xff0c;人们对于AI技术的依赖和需求也在逐渐增加。然而&#xff0c…

使用layui组件库制作进度条

使用layui组件库制作进度条 html代码 <!DOCTYPE html> <html> <head><meta charset"UTF-8"><title>Example</title><!-- 引入 layui 的 CSS 文件 --><link rel"stylesheet" href"https://cdn.staticfil…

(数字图像处理MATLAB+Python)第四章图像正交变换-第四、五节:Radon变换和小波变换

文章目录一&#xff1a;Radon变换&#xff08;1&#xff09;Radon变换原理&#xff08;2&#xff09;Radon变换实现&#xff08;3&#xff09;Radon变换性质&#xff08;4&#xff09;Radon变换应用二&#xff1a;小波变换&#xff08;1&#xff09;小波A&#xff1a;定义B&…

盐城北大青鸟告诉你互联网大厂的哪些岗位不限专业?

进大厂是毕业生、职场人梦寐以求的工作&#xff01; 除了高薪以外&#xff0c;大厂具有舒适的工作环境&#xff0c;一流高校的同事&#xff0c;高额的住房补贴&#xff0c;健身房&#xff0c;下午茶&#xff0c;重点是还有营养丰富的员工餐&#xff01; 那互联网公司都有什么…

Adaptive AUTOSAR——State Management(VRTE 3.0 R21-11)

状态管理是自适应平台服务中的一个功能集群。 在自适应平台中&#xff0c;状态决定了一组活动的自适应应用程序。 特定于项目的应用程序&#xff0c;即状态管理器&#xff0c;决定何时请求状态更改&#xff0c;从而更改当前活动的应用程序集。状态管理器是特定于项目的&#…

基于NXP iMX8M Mini处理器测试DPDK

By Toradex秦海 1). 简介 DPDK (Data Plane Development Kit) 软件是一组用户空间库和驱动程序&#xff0c;可加速在所有主要 CPU 架构上运行的网络数据包处理工作负载&#xff0c;以便提升整个网络数据服务的QoS。其最早由 Intel 大约 2010年创建&#xff0c;后由6WIND公司发…

【CSS】元素显示与隐藏 ( display 隐藏对象 | visibility 隐藏对象 | overflow 隐藏对象 )

文章目录一、元素的显示与隐藏二、display 隐藏对象1、display 隐藏对象语法说明2、display 显示元素代码示例3、display 隐藏元素代码示例三、visibility 隐藏对象1、visibility 隐藏对象语法说明2、visibility 显示对象代码示例3、visibility 隐藏对象代码示例四、overflow 隐…

96年阿里P7晒出工资单:狠补了这个,真香...

最近一哥们跟我聊天装逼&#xff0c;说他最近从阿里跳槽了&#xff0c;我问他跳出来拿了多少&#xff1f;哥们表示很得意&#xff0c;说跳槽到新公司一个月后发了工资&#xff0c;月入5万多&#xff0c;表示很满足&#xff01;这样的高薪资着实让人羡慕&#xff0c;我猜这是税后…

MongoDB 聚合管道的集合关联($lookup)及合并($unionWith)

目前为止&#xff0c;我们已经介绍了一部分聚合管道中的管道参数&#xff1a; $match&#xff1a;文档过滤 $group&#xff1a;文档分组&#xff0c;并介绍了分组中的常用操作&#xff1a;$addToSet&#xff0c;$avg&#xff0c;$sum&#xff0c;$min&#xff0c;$max等。 $add…

可用的rtsp ,rtmp地址以及使用VLC和ffmpeg 播放视频流

可用的 rtmp地址: rtmp://ns8.indexforce.com/home/mystream 可用的 rtsp地址: rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4 可搭配VLC播放器使用&#xff0c;以及虚幻4 流媒体使用&#xff0c;实现直播效果 1.使用VLC 播放&#xff1a;https://www.vi…

某某客户的一次勒索病毒应急响应

Lockbit勒索病毒应急响应背景1、应急处理排查2、勒索病毒来源分析3、勒索病毒分析4、勒索病毒解密5、主机分析分析6、后续安全加固和改进措施结论背景 美好的周六刚开始&#xff0c;眼睛一睁&#xff0c;领导就发消息&#xff0c;说某客户中了勒索病毒&#xff0c;特别着急&am…

2023年第三届智能机器人与系统国际会议(ISoIRS 2023) | IEEE-CPS独立出版

2023年第三届智能机器人与系统国际会议(ISoIRS 2023) | IEEE-CPS独立出版 会议简介 Brief Introduction 2023年第三届智能机器人与系统国际会议(ISoIRS 2023) 会议时间&#xff1a;2023年5月26日-28日 召开地点&#xff1a;中国长沙 大会官网&#xff1a;www.isoirs.org ISoIRS…

项目打包记录提交id

某天上午正在摸鱼的小邓&#xff0c;突然被领导拉倒一个2年前项目的现场问题沟通群&#xff0c;说是现场数据无法入库&#xff0c;需要排查&#xff0c;奈何不知道版本&#xff0c;无奈的小邓值得用时间记录一个点一个点的从gitlab中查找&#xff0c;为了防止后续提供到现场的版…

基于DSP+FPGA的机载雷达伺服控制系统的硬件设计与开发(一)总体设计

2.1 功能要求及性能指标 2.1.1 功能要求 &#xff08;1&#xff09;具备方位和俯仰两轴运动的能力&#xff1b; &#xff08;2&#xff09;方位轴可实现预置、周扫和扇扫功能&#xff1b; &#xff08;3&#xff09;俯仰轴可实现预置功能。 2.1.2 性能指标 &#xff08;1&#…

江南爱窗帘十大品牌,怎么合理的搭配窗帘配色

窗帘行业圈&#xff1a;窗帘行业内部交流圈&#xff0c;窗帘从业者的交流内部圈。 当阳光照进房间的那一刻&#xff0c; 光线给空间带来了无限的可能。 窗边的帘帐既是美丽的风景 又是可爱的魔术师。 在光影变幻的时空里 让你的生活布满温馨和奇幻。 1.窗帘材质怎么选 窗帘的材…

Voting_Averaging算法预测银行客户流失率

Voting_Averaging算法预测银行客户流失率 描述 为了防止银行的客户流失&#xff0c;通过数据分析&#xff0c;识别并可视化哪些因素导致了客户流失&#xff0c;并通过建立一个预测模型&#xff0c;识别客户是否会流失&#xff0c;流失的概率有多大。以便银行的客户服务部门更…

Qt Quick - 分隔器综述

Qt Quick - 分隔器综述一、概述二、MenuSeparator 控件1. 用法&#xff1a;三、ToolSeparator 控件1. 用法一、概述 Qt Quick Controls 提供了多种分隔符&#xff0c;其实就是分割一下MenuBar和ToolBar里面的内容。 控件功能MenuSeparator将菜单中的一组项目与相邻项目分开To…

高效部署Redis Sentinel模式(哨兵模式),手把手教学

Redis Sentinel模式部署前言一、服务器部署同版本的redis1、换软件源在yum拉取包的时候启用remi源二、修改配置文件1.修改/etc/redis.conf2.配置/etc/redis/sentinel.conf三、启动redis服务1、启动服务2、连接redis3、检查redis前言 这里就不过多的解释高可用的好处了&#xf…

一文吃透Http协议

Http 协议 1. 初始 Http Http 协议 , 是应用层最为广泛使用的协议 , Http 就是浏览器和服务器之间的桥梁. Http 是基于 TCP 协议实现的 , 通常我们输入搜索框中的网址 (URL) , 浏览器就会根据这个 URL 构造出一个 Http 请求 , 发送给服务器. 服务器就会返回一个 Http 响应(包…