VUE typescript 调用stompjs[Rabbit MQ]

npm拉下来最新的2.3.9版本,发现一些原来Js代码已经不能用了。顺便解读了下最新定义的内容

// <reference types="node" />export const VERSIONS: {V1_0: string;V1_1: string;V1_2: string;supportedVersions: () => string[];
};export class Client {connected: boolean;counter: number;heartbeat: {incoming: number;outgoing: number;};maxWebSocketFrameSize: number;subscriptions: {};ws: WebSocket;debug(...args: string[]): any;connect(headers: { login: string; passcode: string; host?: string | undefined }, // 头部connectCallback: (frame?: Frame) => any, // 返回消息的监听器,从服务器收消息errorCallback?: (error: Frame | string) => any, // 错误信息的监听器): any;connect(headers: {}, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any;connect(login: string,passcode: string,connectCallback: (frame?: Frame) => any,errorCallback?: (error: Frame | string) => any,host?: string,): any;disconnect(disconnectCallback: () => any, headers?: {}): any; // 拆连接send(destination: string, headers?: {}, body?: string): any;subscribe(destination: string, callback?: (message: Message) => any, headers?: {}): Subscription;unsubscribe(id: string): void;begin(transaction: string): any;commit(transaction: string): any;abort(transaction: string): any;ack(messageID: string, subscription: string, headers?: {}): any;nack(messageID: string, subscription: string, headers?: {}): any;
}export interface Subscription {id: string;unsubscribe(): void;
}export interface Message extends Frame {ack(headers?: {}): any;nack(headers?: {}): any;
}export class Frame {command: string;headers: {};body: string;constructor(command: string, headers?: {}, body?: string);toString(): string;static sizeOfUTF8(s: string): number;static unmarshall(datas: any): any;static marshall(command: string, headers?: {}, body?: string): any;
}export function client(url: string, protocols?: string | string[]): Client;
export function over(ws: WebSocket): Client;
export function overTCP(host: string, port: number): Client;
export function overWS(url: string): Client;
export function setInterval(interval: number, f: (...args: any[]) => void): NodeJS.Timer;
export function clearInterval(id: NodeJS.Timer): void;ChatGPT
typescript
Copy code
/// <reference types="node" />// 定义了支持的 STOMP 协议版本
export const VERSIONS: {V1_0: string;V1_1: string;V1_2: string;supportedVersions: () => string[];
};// 定义了 STOMP 客户端类
export class Client {connected: boolean; // 标识客户端是否连接counter: number; // 消息计数器heartbeat: { // 心跳配置incoming: number; // 接收心跳频率outgoing: number; // 发送心跳频率};maxWebSocketFrameSize: number; // WebSocket 最大消息帧大小subscriptions: {}; // 订阅列表ws: WebSocket; // WebSocket 连接// 调试日志函数debug(...args: string[]): any;// 连接到 STOMP 服务器的方法,支持多种重载形式connect(headers: { login: string; passcode: string; host?: string | undefined }, // 连接头信息connectCallback: (frame?: Frame) => any, // 连接成功的回调函数errorCallback?: (error: Frame | string) => any, // 连接错误的回调函数): any;connect(headers: {}, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any;connect(login: string,passcode: string,connectCallback: (frame?: Frame) => any,errorCallback?: (error: Frame | string) => any,host?: string,): any;// 断开与 STOMP 服务器的连接disconnect(disconnectCallback: () => any, headers?: {}): any;// 发送消息到指定目的地send(destination: string, headers?: {}, body?: string): any;// 订阅指定目的地的消息subscribe(destination: string, callback?: (message: Message) => any, headers?: {}): Subscription;// 取消订阅unsubscribe(id: string): void;// 开启事务begin(transaction: string): any;// 提交事务commit(transaction: string): any;// 回滚事务abort(transaction: string): any;// 手动确认消息ack(messageID: string, subscription: string, headers?: {}): any;// 手动否认消息nack(messageID: string, subscription: string, headers?: {}): any;
}// 订阅对象接口
export interface Subscription {id: string; // 订阅 IDunsubscribe(): void; // 取消订阅方法
}// 消息对象接口,扩展自 Frame
export interface Message extends Frame {ack(headers?: {}): any; // 手动确认消息方法nack(headers?: {}): any; // 手动否认消息方法
}// STOMP 帧对象类
export class Frame {command: string; // 帧命令headers: {}; // 帧头部body: string; // 帧主体constructor(command: string, headers?: {}, body?: string); // 构造函数// 将帧对象转换为字符串toString(): string;// 计算 UTF-8 编码字符串的大小static sizeOfUTF8(s: string): number;// 反序列化 STOMP 帧static unmarshall(datas: any): any;// 序列化 STOMP 帧static marshall(command: string, headers?: {}, body?: string): any;
}// 创建 STOMP 客户端的辅助函数
export function client(url: string, protocols?: string | string[]): Client;// 使用现有的 WebSocket 连接创建 STOMP 客户端的辅助函数
export function over(ws: WebSocket): Client;// 使用 TCP 连接创建 STOMP 客户端的辅助函数
export function overTCP(host: string, port: number): Client;// 使用 WebSocket 连接地址创建 STOMP 客户端的辅助函数
export function overWS(url: string): Client;// 发送客户端心跳
export function setInterval(interval: number, f: (...args: any[]) => void): NodeJS.Timer;// 取消发送客户端心跳
export function clearInterval(id: NodeJS.Timer): void;

然后写一段简短的代码:

<script lang="ts" setup>
import { ref, inject, onMounted, onBeforeUnmount, defineProps, watch } from 'vue'
import Stomp from 'stompjs'const MQTT_SERVICE = 'ws://localhost:15674/ws' // mq服务地址const MQTT_USERNAME = 'user' // mq连接用户名const MQTT_PASSWORD = '123456' // mq连接密码function connectMQ() {const socket = new WebSocket(MQTT_SERVICE)const stompClient = Stomp.over(socket)stompClient.heartbeat.outgoing = 0stompClient.heartbeat.incoming = 0const onConnected = () => {console.log('登录成功!')stompClient.subscribe('a11022a6-ad17-459e-8b23-1ca6599af4f9', onMessageReceived) // 订阅需要的队列}const onMessageReceived = (message: { body: any }) => {console.log('返回数据:', message.body)}const onError = (error: any) => {console.error('RabbitMQ连接失败,错误原因:', error)console.error('5秒后重新连接......')window.setTimeout(() => {connectMQ()}, 5000)}stompClient.connect(MQTT_USERNAME, MQTT_PASSWORD, onConnected, onError, '/')
}onMounted(() => {connectMQ()
})
</script>

然后去rabbitmq管理器给队列发个点对点消息:


试了下,能收到消息


但是出现一个问题,连接质量似乎不怎么好啊,老是掉线:

dashboard.vue:33 RabbitMQ连接失败,错误原因: Whoops! Lost connection to ws://localhost:15674/ws

看来连接质量不怎么好啊,加上个心跳,每15s跳一次:
前面代码关闭了下推,我们加上个上报看看,默认是10s一次,前面都设置为0了:
By default, stomp.js defines a heartbeat of 10000,10000 (to send and receive heartbeats every 10 seconds).

<script lang="ts" setup>
import { ref, inject, onMounted, onUnmounted, defineProps, watch } from 'vue'
import Stomp from 'stompjs'const MQTT_SERVICE = 'ws://localhost:15674/ws' // mq服务地址const MQTT_USERNAME = 'user' // mq连接用户名const MQTT_PASSWORD = '123456' // mq连接密码let heartbeat: NodeJS.Timer | undefined = undefinedfunction connectMQ() {const socket = new WebSocket(MQTT_SERVICE)const stompClient = Stomp.over(socket)stompClient.heartbeat.outgoing = 15000stompClient.heartbeat.incoming = 0const onConnected = () => {console.log('登录成功!')stompClient.subscribe('a11022a6-ad17-459e-8b23-1ca6599af4f9', onMessageReceived)}const onMessageReceived = (message: { body: any }) => {console.log('返回数据:', message.body)}const onError = (error: any) => {console.error('RabbitMQ连接失败,错误原因:', error)console.error('5秒后重新连接......')window.setTimeout(() => {connectMQ()}, 5000)}stompClient.connect(MQTT_USERNAME, MQTT_PASSWORD, onConnected, onError, '/')heartbeat = Stomp.setInterval(15000, () => {console.log('心跳呀')})
}onMounted(() => {connectMQ()
})onUnmounted(() => {if (heartbeat) {Stomp.clearInterval(heartbeat)}
})
</script>

这下稳定多了:

正式代码可以考虑把接收的消息数据和方法都放到vuex的store里

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

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

相关文章

面试经典算法系列之二叉树5 -- 二叉树的前序遍历

面试经典算法20 - 二叉树的前序遍历 LeetCode.144 公众号&#xff1a;阿Q技术站 问题描述 给你二叉树的根节点 root &#xff0c;返回它节点值的 前序 遍历。 示例 1&#xff1a; 输入&#xff1a;root [1,null,2,3] 输出&#xff1a;[1,2,3]示例 2&#xff1a; 输入&…

结合ArcGIS+SWAT模型+Century模型:流域生态系统水-碳-氮耦合过程模拟

原文链接&#xff1a;结合ArcGISSWAT模型Century模型&#xff1a;流域生态系统水-碳-氮耦合过程模拟https://mp.weixin.qq.com/s?__bizMzUzNTczMDMxMg&tempkeyMTI2NV9sMGRZNUJoVkNVc1ZzSzRuMl9XXzhqX0R3cXpESWFwM1E4cFY4ejNqWFh3VUl0dlZkNWk4b20ydFdFTy1xS2ZObGN0Z0ZXSjly…

怎么在外地控制自家的电视

怎么在外地控制自家的电视 随着科技的进步和智能家居的普及&#xff0c;远程控制家中的电器设备已经成为现实。电视作为家庭娱乐的中心&#xff0c;远程控制功能更是备受关注。那么&#xff0c;如何在外地控制自家的电视呢&#xff1f;本文将为你提供详细的步骤和有价值的信息…

医院订餐平台:为患者提供贴心服务的创新解决方案

在现代医疗服务中&#xff0c;患者的就餐问题一直是一个备受关注的议题。传统的医院饮食服务往往面临着餐品单一、服务不及时等问题&#xff0c;无法满足患者的个性化需求。为了提高患者的就餐体验&#xff0c;医院订餐平台应运而生&#xff0c;通过数字化、个性化的服务&#…

【域适应】基于深度域适应MMD损失的典型四分类任务实现

关于 MMD &#xff08;maximum mean discrepancy&#xff09;是用来衡量两组数据分布之间相似度的度量。一般地&#xff0c;如果两组数据分布相似&#xff0c;那么MMD 损失就相对较小&#xff0c;说明两组数据/特征处于相似的特征空间中。基于这个想法&#xff0c;对于源域和目…

【HTML】制作一个简单的线性动画

目录 前言 HTML部分 CSS部分 JS部分 效果图 总结 前言 无需多言&#xff0c;本文将详细介绍一段HTML代码&#xff0c;具体内容如下&#xff1a; 开始 首先新建文件夹&#xff0c;创建一个文本文档&#xff0c;两个文件夹&#xff0c;其中HTML的文件名改为[index.html]&am…

前端对接fastGPT流式数据+打字机效果

首先在对接api时 参数要设置stream: true, const data {chatId: abc,stream: true,//这里true返回流式数据detail: false,variables: {uid: sfdsdf,name: zhaoyunyao,},messages: [{ content: text, role: user }]}; 不要用axios发请求 不然处理不了流式数据 我这里使用fetch …

赋能技术 助锂制造|青软青之助力锂电检测行业数字化升级

在全球范围内&#xff0c;新能源转型已成为时代的必然选择。随着“双碳”目标的深入推进&#xff0c;这一趋势愈发明显。而作为新能源领域的一颗璀璨明珠&#xff0c;锂电池的研发、产业链建设和技术创新&#xff0c;无疑是这场能源革命的核心所在。其产业链的日趋完善、技术的…

通过WebShell登录SQL Server主机并使用SSRS报表服务

背景信息 RDS SQL Server提供了WebShell功能&#xff0c;允许用户通过Web界面登录到RDS SQL Server实例的操作系统中&#xff0c;并在该操作系统中执行命令、上传下载文件等操作。WebShell功能方便用户对RDS SQL Server实例的管理和维护&#xff0c;特别是在无法使用SSH客户端的…

PyTorch-Lightning:trining_step的自动优化

文章目录 PyTorch-Lightning&#xff1a;trining_step的自动优化总结&#xff1a; class _ AutomaticOptimization()def rundef _make_closuredef _training_stepclass ClosureResult():def from_training_step_output class Closure PyTorch-Lightning&#xff1a;trining_ste…

纯小白蓝桥杯备赛笔记--DAY14(计算几何)

文章目录 计算几何基础平面几何距离圆的周长和面积圆与圆之间的关系&#xff1a;海伦公式计算三角形面积点到直线的距离 点积和叉积例题&#xff1a; 点和线的关系点的表示形式和代码判断点在直线的那边点到线的垂足点到线的距离例题-1242例题-1240升级--点到线段的距离--1285 …

基于级联H桥的多电平逆变器PWM控制策略的simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 5.完整工程文件 1.课题概述 级联H桥&#xff08;CHB&#xff09;多电平逆变器是一种通过多个H桥单元级联实现更高电压等级和更高质量输出波形的电力电子转换装置。这种逆变器在高压大功率场合应用广泛&am…