采用轮询的方式实现在线人数

轮询主要通过定时器来实现

1.获取设备id

这里需要像后端传入正在观看视频的设备Id号,区分不同的用户设备,确保每个设备在进行视频播放时能被唯一识别。通过设备ID,你可以追踪每个设备的观看状态(例如,记录每个设备的播放情况,获取每个设备是否正在观看视频等)。

使用@fingerprintjs/fingerprintjs": "^4.4.3"和cookies:获取浏览器的唯一标识,具体代码如下:

import FingerprintJS from "@fingerprintjs/fingerprintjs";
// 获取设备Id
const getDeviceId = async () => {
  let deviceId = VueCookies.get("deviceId");
  if (!deviceId) {
    // 通过@fingerprintjs/fingerprintjs插件获取浏览器设备
    const fpPromise = await FingerprintJS.load();
    const result = await fpPromise.get();
    deviceId = result.visitorId;
    // 过期时间,单位为天(-1 表示会话级 Cookie,浏览器关闭就删除)即永久保存
    VueCookies.set("deviceId", deviceId, -1);
  }
  loginStore.saveDeviceId(deviceId);
};

2.确定要轮询的事件

const onlineCount = ref(1);
const reportVideoPlayOnline = async () => {
  if (!fileId.value) {
    return;
  }
  let result = await proxy.Request({
    url: proxy.Api.reportVideoPlayOnline,
    params: {
      fileId: fileId.value,
      deviceId: loginStore.deviceId,
    },
    //  这是一个自定义配置项,
    // 用于控制 是否在请求出错时弹出错误提示(或进行错误处理)。
    showError: false,
  });
  if (!result) {
    return;
  }
  onlineCount.value = result.data;
};

3.使用定时器进行轮询

let timer = ref(null);
const startTimer = () => {
  timer.value = setInterval(() => {
    reportVideoPlayOnline();
  }, 5000);
};

4.在组件销毁之前,清空定时器

onBeforeUnmount(() => {
  cleanTimer()
});
const cleanTimer=()=>{
  if(timer.value!==null){
    clearInterval(timer.value)
    timer.value=null
  }
}

你可能感兴趣的:(服务器,前端,运维)