科技 > 操作系统 > Windows

如何实现设备组缓存的正确清除?——基于心跳请求和心跳响应的解决方案

21人参与 2024-08-02 Windows

在设备组关闭后,如何保证缓存中的设备组信息能够正确清除?本文将介绍如何通过前端实现设备组心跳检测和缓存清除,以及通过后端实现缓存清除的逻辑来解决该问题。我们还将详细讨论如何利用心跳请求和心跳响应来实现设备组缓存的正确清除,并提供基于vue和springboot的代码示例。

一、问题描述

在开发设备管理系统时,我们经常需要保证设备组在关闭后能够从缓存中正确删除,以避免占用过多的系统资源。

示例:若依前后端分离框架,如果用户使用当前设备组,那么当前设备组会被写进缓存里,然后被占用,其他用户则不能使用该设备组;如果用户退出当前设备组,那么将从缓存里删掉该设备,但是很难保证的情况是,如果用户突然关闭浏览器,或者不正常关闭页面、退出帐号,都不能正常从缓存里删除该设备组,如何保证不管怎么样退出,都能从缓存中删掉该设备组?

二、问题分析

前端使用一个定时器,每隔5秒向后端发送请求,告知后端当前设备组是否还在使用中。后端使用一个device_group_key + id来保存设备组是否被占用的状态,当用户加入设备组时,将该设备组的状态设置为占用,并设定过期时间为10秒;当用户退出设备组时,从device_group_key + id中删除该设备组的状态。如果后端收到了一段时间内没有收到定时器请求的设备组,就会自动将该设备组从device_group_key + id中删除。

当用户正常退出设备组时,前端会清除定时器并向后端发送请求,告知后端该设备组已经退出使用。如果用户异常退出设备组,则后端会在一段时间后自动删除该设备组。

三、解决方案

你的前端代码看起来已经调用了后端接口将设备组放入缓存中了。如果你想实现定时向后端发送请求,告知后端该设备组是否还在使用中,可以使用setinterval函数创建一个定时器,每隔一定时间向后端发送请求,告知后端该设备组仍在使用中。

前端

deviceinfo是预选设备组,currentdeviceinfo是当前设备组,devicegroupkeys是缓存中的设备组,代码示例如下:

<template>
  <div>
    <el-form :model="queryparams" ref="queryform" size="small" :inline="true" v-show="showsearch" label-width="60px">
      <el-form-item label="设备组" prop="group">
        <el-select v-model="devicegroup" placeholder="请选择" @change="selectdevicegroup">
          <!-- 选择devicegrouplist -->
          <el-option v-for="item in devicegrouplist" :key="item.devicegroup" :label='"第" + item.devicegroup + "组"'
            :value="item.devicegroup" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-circle-check" size="mini" @click="joindevicegroup">确定</el-button>
        <el-button icon="el-icon-remove-outline" size="mini" type="info" @click="leavedevicegroup">退出当前设备组</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
    /** 加入设备组 */
	async joindevicegroup(){
	//查询预选的设备组是否被占用
	if (this.devicegroupkeys.includes(`${this.deviceinfo.devicegroup}`)) {
	        this.$message({
	          message: "该设备组已被使用",
	          type: "warning",
	        });
	        return;
	      }
	      //预选设备组没有被占用,如果当前设备组被自己占用,则将其从缓存中删除
	      if (this.currentdeviceinfo.devicegroup !== "") {
	        await deletedevicegroupkey(this.currentdeviceinfo.devicegroup);
	        clearinterval(this.timer);
	      }
	      //否则将deviceinfo预选设备组放入currentdeviceinfo当前设备组
	      this.currentdeviceinfo = json.parse(json.stringify(this.deviceinfo)) || null;
	      // 将currentdeviceinfo中的devicegroup放入缓存,用setdevicegroupkey方法
	      await setdevicegroupkey(this.currentdeviceinfo.devicegroup);
	      // 开启定时器
	      this.setinterval();
	}
    /** 定义一个定时器,每隔5秒钟,调用一次senddeviceheartbeat方法 */
    setinterval() {
      // 如果currentdeviceinfo.devicegroup为空,则停止定时器
      if (this.currentdeviceinfo.devicegroup == "") {
        clearinterval(this.timer);
      } else {
        this.timer = setinterval(() => {
          this.senddeviceheartbeat();
        }, 5000);
      }
    },

    // 发送心跳请求的函数
    senddeviceheartbeat() {
      // 如果this.currentdeviceinfo.devicegroup为空,则停止定时器
      if (this.currentdeviceinfo.devicegroup == "") {
        clearinterval(this.timer);
      }
      // 发送请求deviceheartbeat
    deviceheartbeat(this.currentdeviceinfo.devicegroup).then((response) => {
        // console.log(response);
        if (response === 0) {
          // 心跳成功,设备组仍在使用中
        } else {
          // 心跳失败,设备组已经退出使用
          this.$message({
            message: "设备组已经退出使用",
            type: "warning",
          });
          clearinterval(this.timer);
        }
      });
    },

然后在用户正常退出设备组时,清除定时器并向后端发送请求,告知后端该设备组已经退出使用。代码示例如下:

leavedevicegroup() {
      if (this.currentdeviceinfo.devicegroup != "") {
        deletedevicegroupkey(this.currentdeviceinfo.devicegroup).then((response) => {
          //清空currentdeviceinfo
          this.currentdeviceinfo = {
            devicegroup: "",
          };
        });
      }
      // 停止定时器
      clearinterval(this.timer);
}

计时器应该在用户正常退出设备组和关闭页面时被清除。在vue中,可以通过在beforedestroy()生命周期钩子中清除计时器,例如:

beforedestroy() {
  clearinterval(this.timer);
}

这里假设你的计时器是通过setinterval()创建的,并将其存储在vue实例的timer属性中。当vue实例被销毁时,beforedestroy()生命周期钩子会被调用,此时可以清除计时器。

后端

获取缓存中devicegroup所有的key

    /**
     * 获取缓存中devicegroup所有的key
     */
    @getmapping("/getdevicegroupkeys")
    public list<integer> getdevicegroupkeys() {
        //将redis中device_group的的基本对象列表,使用rediscache.keys()方法获取
        string[] keys = rediscache.keys(cacheconstants.device_group_key + "*").toarray(new string[0]);
        //将keys中的值,去掉前缀,只保留1,2,3,4,5
        list<integer> list = new arraylist<>();
        for (string key : keys) {
            list.add(integer.parseint(key.substring(cacheconstants.device_group_key.length())));
        }
        //将list从小到大排序
        list.sort((o1, o2) -> o1 - o2);
        return list;
    }

实现将设备组放入缓存

    /**
     * 将设备组放入缓存
     */
    @getmapping(value = "/setdevicegroupkey/{id}")
    public string setdevicegroupkey(@pathvariable("id") integer id) {
        rediscache.setcacheobject(cacheconstants.device_group_key + id, "true", 10, timeunit.seconds);
        return rediscache.haskey(cacheconstants.device_group_key + id) ? "true" : "false";
    }

在用户正常退出设备组时,你可以实现一个deletedevicegroupkey接口,用于从缓存中删除该设备组。代码示例如下:

    /**
     * 将设备组从缓存中删除
     */
    @getmapping("/deletedevicegroupkey/{id}")
    public string deletedevicegroupkey(@pathvariable("id") integer id) {
        rediscache.deleteobject(cacheconstants.device_group_key + id);
        return rediscache.haskey(cacheconstants.device_group_key + id) ? "false" : "true";
    }

你可以实现一个deviceheartbeat接口,用于更新设备组在缓存中的存活时间。代码示例如下:

    /**
     * 检查设备组是否还在使用,心跳请求处理接口
     */
    @postmapping(value = "/deviceheartbeat/{id}")
    public string deviceheartbeat(@pathvariable("id") integer id) {
        // 检查设备组是否存在于缓存中
        if (!rediscache.haskey(cacheconstants.device_group_key + id)) {
            // 设备组不存在,返回心跳失败
            return "device group not found!";
        } else {
            // 更新设备组的心跳时间
            rediscache.expire(cacheconstants.device_group_key + id, 10, timeunit.seconds);
            // 返回心跳成功
            return "heartbeat successfully!";
        }
    }

如果用户异常退出设备组,你可以在后端实现一个定时任务,定时检查缓存中的设备组是否过期,如果过期则删除该设备组。代码示例如下:

	/**
	 * 定时任务:删除过期的设备组,每隔10秒检查一次缓存中的设备组是否超时
	 */
    @scheduled(fixeddelay = 10000)
    public void checkdevicegroupkey() {
        // 获取当前时间
        date now = new date();
  		set<object> devicegroupkeys = rediscache.keys(cacheconstants.device_group_key + "*");
        // 遍历缓存中的设备组device_group_key,检查是否超时
        for (object devicegroupkey : devicegroupkeys) {
            // 获取缓存中的设备组
            string key = (string) devicegroupkey;
            // 如果缓存中的设备组存在
            if (rediscache.haskey(key)) {
                // 获取缓存中的设备组的最后一次心跳时间
                date lastheartbeattime = rediscache.getcacheobject(key);
                // 计算当前时间和最后一次心跳时间的差值
                long diff = now.gettime() - lastheartbeattime.gettime();
                // 如果差值大于10秒,说明设备组已经超时,将设备组从缓存中删除
                if (diff > 10000) {
                    rediscache.deleteobject(key);
                }
            }
        }
    }

也可以限制哪几个设备组需要被清除

    /**
     * 定时任务:删除过期的设备组,每隔10秒检查一次缓存中的设备组是否超时
     */
    @scheduled(fixeddelay = 10000)
    public void checkdevicegroupkey() {
        // 获取当前时间
        date now = new date();

        // 遍历缓存中的设备组device_group_key,检查是否超时
        for (int i = 1; i <= 16; i++) {
            // 获取缓存中的设备组
            string key = cacheconstants.device_group_key + i;
            // 如果缓存中的设备组存在
            if (rediscache.haskey(key)) {
                // 获取缓存中的设备组的最后一次心跳时间
                date lastheartbeattime = rediscache.getcacheobject(key);
                // 计算当前时间和最后一次心跳时间的差值
                long diff = now.gettime() - lastheartbeattime.gettime();
                // 如果差值大于10秒,说明设备组已经超时,将设备组从缓存中删除
                if (diff > 10000) {
                    rediscache.deleteobject(key);
                }
            }
        }
    }

后端缓存时间设置为10秒钟,前端每隔5秒向后端发送请求,那么在正常情况下,如果前端正常关闭,后端会在10秒钟后自动清除该设备组的缓存。

如果前端异常关闭,那么后端会在10秒钟后检测到该设备组的心跳信号已经停止,然后自动清除该设备组的缓存。

因此,这种方法可以保证在大多数情况下能够及时清除缓存,但是仍然可能存在一些极端情况导致缓存无法及时清除,比如网络故障等。

(0)

您想发表意见!!点此发布评论

推荐阅读

npm如何清空缓存并重新打包?

08-02

win10修改conda环境和缓存默认路径

08-02

CentOS编译安装OpenSSL 3.3.1

08-02

最简单方便实现ubuntu远程桌面方法

08-02

ubuntu22.04 安装 wine8.0

08-02

Mac 苹果电脑下载安装《植物大战僵尸杂交版2.0.88》详细指南教程(含已损坏打不开等问题解决)

08-02

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论