refactor(web-antd): 用 SSE 替代 WebSocket 实现通知和电表数据实时推送

This commit is contained in:
2025-09-06 13:15:36 +08:00
parent 6f987f29ef
commit 621674ed1f
3 changed files with 79 additions and 88 deletions

View File

@@ -16,8 +16,6 @@ import { $t } from '#/locales'
import { useDictStore } from './dict' import { useDictStore } from './dict'
import { initWebSocket, getWebSocketService } from '#/api/websocket'
export const useAuthStore = defineStore('auth', () => { export const useAuthStore = defineStore('auth', () => {
const accessStore = useAccessStore() const accessStore = useAccessStore()
const userStore = useUserStore() const userStore = useUserStore()
@@ -81,13 +79,6 @@ export const useAuthStore = defineStore('auth', () => {
try { try {
await seeConnectionClose() await seeConnectionClose()
await doLogout() await doLogout()
/**
* 断开websocket连接
*/
const ws = getWebSocketService();
if(ws) {
ws.close();
}
} catch (error) { } catch (error) {
console.error(error) console.error(error)
} finally { } finally {
@@ -128,11 +119,6 @@ export const useAuthStore = defineStore('auth', () => {
} }
userStore.setUserInfo(userInfo) userStore.setUserInfo(userInfo)
/**
* 初始化websocket
*/
initWebSocket()
/** /**
* 需要重新加载字典 * 需要重新加载字典
* 比如退出登录切换到其他租户 * 比如退出登录切换到其他租户

View File

@@ -1,21 +1,21 @@
import type { NotificationItem } from '@vben/layouts'; import type { NotificationItem } from '@vben/layouts'
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue'
import { useAppConfig } from '@vben/hooks'; import { useAppConfig } from '@vben/hooks'
import { SvgMessageUrl } from '@vben/icons'; import { SvgMessageUrl } from '@vben/icons'
import { $t } from '@vben/locales'; import { $t } from '@vben/locales'
import { useAccessStore, useUserStore } from '@vben/stores'; import { useAccessStore, useUserStore } from '@vben/stores'
import { useEventSource } from '@vueuse/core'; import { useEventSource } from '@vueuse/core'
import { notification } from 'ant-design-vue'; import { notification } from 'ant-design-vue'
import dayjs from 'dayjs'; import dayjs from 'dayjs'
import { defineStore } from 'pinia'; import { defineStore } from 'pinia'
const { apiURL, clientId, sseEnable } = useAppConfig( const { apiURL, clientId, sseEnable } = useAppConfig(
import.meta.env, import.meta.env,
import.meta.env.PROD, import.meta.env.PROD,
); )
export const useNotifyStore = defineStore( export const useNotifyStore = defineStore(
'app-notify', 'app-notify',
@@ -23,18 +23,18 @@ export const useNotifyStore = defineStore(
/** /**
* return才会被持久化 存储全部消息 * return才会被持久化 存储全部消息
*/ */
const notificationList = ref<NotificationItem[]>([]); const notificationList = ref<NotificationItem[]>([])
const sseList = ref<string[]>(["111"]); const sseList = ref<string[]>(["111"])
const userStore = useUserStore(); const userStore = useUserStore()
const userId = computed(() => { const userId = computed(() => {
return userStore.userInfo?.userId || '0'; return userStore.userInfo?.userId || '0'
}); })
const notifications = computed(() => { const notifications = computed(() => {
return notificationList.value.filter( return notificationList.value.filter(
(item) => item.userId === userId.value, (item) => item.userId === userId.value,
); )
}); })
/** /**
* 开始监听sse消息 * 开始监听sse消息
@@ -44,40 +44,45 @@ export const useNotifyStore = defineStore(
* 未开启 不监听 * 未开启 不监听
*/ */
if (!sseEnable) { if (!sseEnable) {
return; return
} }
const accessStore = useAccessStore(); const accessStore = useAccessStore()
const token = accessStore.accessToken; const token = accessStore.accessToken
const sseAddr = `${apiURL}/resource/sse?clientid=${clientId}&Authorization=Bearer ${token}`; const sseAddr = `${apiURL}/resource/sse?clientid=${clientId}&Authorization=Bearer ${token}`
const { data } = useEventSource(sseAddr, [], { const { data } = useEventSource(sseAddr, [], {
autoReconnect: { autoReconnect: {
delay: 1000, delay: 1000,
onFailed() { onFailed() {
console.error('sse重连失败.'); console.error('sse重连失败.')
}, },
retries: 3, retries: 3,
}, },
}); })
watch(data, (message) => { watch(data, (message) => {
if (!message) return; if (!message) return
console.log(`接收到消息: ${message}`); console.log(`接收到消息: ${message}`)
try { try {
// 尝试解析JSON // 尝试解析JSON
const obj = JSON.parse(message); const obj = JSON.parse(message)
// 检查解析结果是否为对象且不为null // 检查解析结果是否为对象且不为null
if (obj.getType() ==="yvjin"){ if (obj.type === "yvjin") {
sseList.value.join(message) sseList.value.push(message)
}
// 仪表数据
if (obj.type === "meter") {
sseList.value.push(message)
} }
} catch (e) { } catch (e) {
notification.success({ notification.success({
description: message, description: message,
duration: 3, duration: 3,
message: $t('component.notice.received'), message: $t('component.notice.received'),
}); })
notificationList.value.unshift({ notificationList.value.unshift({
// avatar: `https://api.multiavatar.com/${random(0, 10_000)}.png`, 随机头像 // avatar: `https://api.multiavatar.com/${random(0, 10_000)}.png`, 随机头像
@@ -87,12 +92,12 @@ export const useNotifyStore = defineStore(
message, message,
title: $t('component.notice.title'), title: $t('component.notice.title'),
userId: userId.value, userId: userId.value,
}); })
// 需要手动置空 vue3在值相同时不会触发watch // 需要手动置空 vue3在值相同时不会触发watch
data.value = null; data.value = null
} }
}); })
} }
/** /**
@@ -102,10 +107,10 @@ export const useNotifyStore = defineStore(
notificationList.value notificationList.value
.filter((item) => item.userId === userId.value) .filter((item) => item.userId === userId.value)
.forEach((item) => { .forEach((item) => {
item.isRead = true; item.isRead = true
}); })
} }
function getsseList(){ function getsseList() {
console.log(sseList.value) console.log(sseList.value)
return sseList.value return sseList.value
} }
@@ -115,7 +120,7 @@ export const useNotifyStore = defineStore(
* @param item 通知 * @param item 通知
*/ */
function setRead(item: NotificationItem) { function setRead(item: NotificationItem) {
!item.isRead && (item.isRead = true); !item.isRead && (item.isRead = true)
} }
/** /**
@@ -124,7 +129,7 @@ export const useNotifyStore = defineStore(
function clearAllMessage() { function clearAllMessage() {
notificationList.value = notificationList.value.filter( notificationList.value = notificationList.value.filter(
(item) => item.userId !== userId.value, (item) => item.userId !== userId.value,
); )
} }
/** /**
@@ -141,7 +146,7 @@ export const useNotifyStore = defineStore(
notificationList.value notificationList.value
.filter((item) => item.userId === userId.value) .filter((item) => item.userId === userId.value)
.some((item) => !item.isRead), .some((item) => !item.isRead),
); )
return { return {
$reset, $reset,
@@ -154,11 +159,11 @@ export const useNotifyStore = defineStore(
setRead, setRead,
showDot, showDot,
startListeningMessage, startListeningMessage,
}; }
}, },
{ {
persist: { persist: {
pick: ['notificationList'], pick: ['notificationList'],
}, },
}, },
); )

View File

@@ -1,45 +1,49 @@
<script setup lang="ts"> <script setup lang="ts">
import { useNotifyStore } from '#/store';
import { useAccessStore } from '@vben/stores'; import { useAccessStore } from '@vben/stores';
import FloorTree from '../components/floor-tree.vue';
import { BackTop, message, Spin } from 'ant-design-vue'; import { BackTop, message, Spin } from 'ant-design-vue';
import { Page, VbenCountToAnimator } from '@vben/common-ui'; import { Page, VbenCountToAnimator } from '@vben/common-ui';
import { ref, onMounted, onBeforeUnmount, reactive } from 'vue'; import { ref, onMounted, onBeforeUnmount, reactive, watch } from 'vue';
import FloorTree from '../components/floor-tree.vue';
import { getWebSocketService } from '#/api/websocket';
import { currentReading } from '#/api/property/energyManagement/meterInfo'; import { currentReading } from '#/api/property/energyManagement/meterInfo';
const ws = getWebSocketService(); const notifyStore = useNotifyStore();
const readingData = ref<any>({}); const readingData = ref<any>({});
const readingTime = ref(''); const readingTime = ref('');
let readingLoading = ref(false); const readingLoading = ref(false);
if (ws) { onMounted(() => {
// 使用setOnMessageCallback方法设置消息回调 notifyStore.startListeningMessage();
ws.setOnMessageCallback((event: MessageEvent) => { // 监听sseList的变化
// 解析数据并更新UI watch(
try { () => notifyStore.sseList,
const data = JSON.parse(event.data); (val) => {
if (data.type === 'meter') { const latestMessage = val[val.length - 1];
if (typeof data.data === 'undefined') {
message.warn('当前楼层暂无电表!'); try {
// 尝试解析消息内容
const parsedMessage = JSON.parse(latestMessage);
console.log('收到sse消息:', parsedMessage);
if (parsedMessage.type === 'meter') {
// 根据消息内容执行相应操作
handleSSEMessage(parsedMessage);
} }
readingData.value = data.data; } catch (e) {
readingTime.value = data.readingTime; console.log('收到非JSON消息:', latestMessage);
// 处理非JSON格式消息
} }
} catch (e) { },
console.error('Error parsing data:'); { deep: true },
} );
readingLoading.value = false; });
});
// 如果需要,也可以设置错误回调 function handleSSEMessage(data: any) {
ws.setOnErrorCallback((error: any) => { if (data.data.length === 0) {
console.log('Error in WebSocket:'); message.warn('当前楼层暂无电表!');
currentReading({ meterType: 0, floorId: 0 }); }
readingLoading.value = false; readingData.value = data.data;
}); readingTime.value = data.readingTime;
}else {
readingLoading.value = false; readingLoading.value = false;
message.warn('websocket未连接请刷新页面重试');
} }
onBeforeUnmount(() => { onBeforeUnmount(() => {
@@ -50,10 +54,6 @@ async function handleSelectFloor(selectedKeys, info) {
if (typeof selectedKeys[0] === 'undefined') { if (typeof selectedKeys[0] === 'undefined') {
return; return;
} }
if (ws.webSocket.readyState !== 1) {
message.warn('websocket未连接请刷新页面重试');
return;
}
readingLoading.value = true; readingLoading.value = true;
await currentReading({ await currentReading({
meterType: 1, meterType: 1,