前言:關于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支持,你可以根據實際需求進行調整和擴展。
?