前言:关于Dexie.js这个前端本地数据库,如何使用IndexedDB来存储数据,并且设置到期自动清理的机制。首先,我需要回忆一下Dexie.js的基本用法,以及IndexedDB的特性。IndexedDB是浏览器中的一种非关系型数据库,适合存储大量结构化数据,而Dexie.js是对它的一个封装,简化了操作。
用户的需求是在数据存储后,能够根据设定的时间自动清理过期数据。这涉及到两个主要部分:一是如何在存储数据时记录存储时间,并设置过期时间;二是如何定期或在访问时检查并删除过期的数据。
首先,在数据模型设计上,需要为每个数据条目添加两个字段,比如createdAt和timestamp。记录数据创建的时间戳,这样,当需要检查数据是否过期时,可以通过这两个字段来计算。
先上效果图:
以下是使用 Dexie.js 实现 IndexedDB 数据到期自动清理的步骤详解:
1. 安装 Dexie
首先,确保你已经安装了 Dexie:
npm install dexie
# 或
yarn add dexie
2. 完整组件封装实现代码 db.js
// db.js - IndexedDB 数据库配置和清理工具
import Dexie from 'dexie';
// 定义数据库结构
class AppDatabase extends Dexie {constructor() {super('C3AppDatabase');// 定义数据库版本和表结构this.version(1).stores({channelIdLogs: '++id, channelId, createdAt', // 示例表// cache: '++id, key, value, timestamp', // 示例缓存表loadApiParms: '++id, timestamp',importSocketList: '++id, dataType, timestamp'// 添加其他表...});// 绑定表到this对象以便直接访问this.channelIdLogs = this.table('channelIdLogs');// this.cache = this.table('cache');this.loadApiParms = this.table('loadApiParms');this.importSocketList = this.table('importSocketList');}// 清理所有表中超过指定天数的数据async cleanupOldData(days = 3) {try {const cutoffDate = new Date();cutoffDate.setDate(cutoffDate.getDate() - days);// 清理channelIdLogs表await this.channelIdLogs.where('createdAt').below(cutoffDate.getTime()).delete();// 清理cache表// await this.cache// .where('timestamp')// .below(cutoffDate.getTime())// .delete();// 清理loadApiParms表await this.loadApiParms.where('timestamp').below(cutoffDate.getTime()).delete();// 清理importSocketList表await this.importSocketList.where('timestamp').below(cutoffDate.getTime()).delete();console.log(`成功清理${days}天前的数据`);return true;} catch (error) {// console.error('清理旧数据时出错:', error);return false;}}// 定期清理(例如每天一次)startAutoCleanup(days = 3, intervalHours = 24) {// 先立即执行一次清理this.cleanupOldData(days);// 然后设置定时器setInterval(() => {this.cleanupOldData(days);}, intervalHours * 60 * 60 * 1000);}
}// 创建数据库实例
const db = new AppDatabase();// 导出数据库实例和清理方法
export { db };// 初始化数据库并启动自动清理
export async function initDatabase() {try {// 打开数据库await db.open();// console.log('数据库已打开')// 启动自动清理(3天前的数据,每天检查一次)db.startAutoCleanup(3, 24);return db;} catch (error) {// console.error('数据库初始化失败:', error)throw error;}
}
注:cache表 我没有用到所以注释了。
3. 使用示例
import { initDatabase, db } from '@/utils/db';async getChannelId(channelId) {try {// 初始化数据库await initDatabase();// 添加测试数据await db.channelIdLogs.add({content: '这是一条测试日志',createdAt: new Date('2020-01-01').getTime() // 旧数据,会被清理});await db.channelIdLogs.add({channelId: channelId,time: nowTime(new Date()),createdAt: Date.now()});// 手动触发清理(可选)await db.cleanupOldData(3);// 查询剩余日志// const allLogs = await db.channelIdLogs.toArray()// console.log('channelId当前日志:', allLogs)} catch (error) {// console.error('应用出错:', error)}},
注:然后别忘了调用方法: 我这里是 传值了, 你随意传,只要是字符串就可以。
我这只是给 channelIdLogs 这个表 添加数据, 如果想给其他表添加数据, 同样的方法 改下表明就可以。
mounted() {this.getChannelId(channelId)
}
4 .最佳实践建议
-
备份重要数据:在执行清理前,考虑对重要数据进行备份
-
用户通知:清理大量数据前通知用户
-
性能监控:监控清理操作的性能,特别是对于大型数据库
-
错误处理:完善错误处理,确保清理失败不会影响应用主要功能
-
测试:编写单元测试验证清理逻辑
这个完整实现提供了基本清理功能、自动定期清理、进度报告和Web Worker支持,你可以根据实际需求进行调整和扩展。