修改了SledDB代码,使得打开更优雅,性能更快

This commit is contained in:
:NoBody: committed 2026-03-31 22:26:23 +08:00
1 parent 9fda014ce6
commit a2510dc4af
6 files changed
+98 -4

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
pub mod define;
pub mod sled_db;
pub mod user_state;
+25 -4
View File
@@ -1,9 +1,26 @@
use std::path::Path;
use std::{
path::{Path, PathBuf},
sync::OnceLock,
};
use super::define::StorageEngine;
use anyhow::Result;
use async_trait::async_trait;
use dashmap::DashMap;
pub static SLED_DB_POOL: OnceLock<DashMap<PathBuf, sled::Db>> = OnceLock::new();
pub fn get_sled_db(path: &Path) -> Result<sled::Db> {
let pool = SLED_DB_POOL.get_or_init(|| DashMap::new());
if let Some(db) = pool.get(path) {
Ok(db.clone())
} else {
let db = sled::open(path)?;
pool.insert(path.to_path_buf(), db.clone());
Ok(db)
}
}
pub fn get_pool() -> &'static DashMap<PathBuf, sled::Db> {
SLED_DB_POOL.get_or_init(|| DashMap::new())
}
pub struct SledDB {
pub sled_db: sled::Db,
}
@@ -11,6 +28,7 @@ pub struct SledDB {
impl SledDB {
pub fn new(path: &Path) -> Result<Self> {
let db = sled::open(path)?;
Ok(Self { sled_db: db })
}
}
@@ -18,7 +36,11 @@ impl SledDB {
#[async_trait]
impl StorageEngine for SledDB {
async fn open(path: &Path) -> Result<Self> {
Self::new(path)
let entry = get_pool().entry(path.to_path_buf());
let sled_db = entry
.or_insert_with(|| sled::open(path).expect("Failed to open sled database"))
.clone();
Ok(SledDB { sled_db })
}
async fn set_raw(&self, key: &[u8], value: &[u8]) -> Result<()> {
@@ -39,7 +61,6 @@ impl StorageEngine for SledDB {
}
}
//INFO: AI写的集成测试
#[cfg(test)]
mod tests {
+44
View File
@@ -0,0 +1,44 @@
use chrono::Datelike;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct UserState {
pub is_checkin_today: bool,
pub checkin_unix_second: u64,
pub checkin_times_in_month: usize,
pub checkin_days: Vec<u32>, //每月在哪天签到了
}
/*
key:用户id
value:UserState的json字符串
*/
impl UserState {
pub fn new() -> Self {
Self {
is_checkin_today: false,
checkin_unix_second: 0,
checkin_times_in_month: 0,
checkin_days: Vec::new(),
}
}
pub fn checkin(&mut self) {
self.is_checkin_today = true;
let unix_time = tokio::time::Instant::now().elapsed().as_secs();
self.checkin_unix_second = unix_time;
self.checkin_times_in_month += 1;
let day = chrono::Utc::now().day();
if !self.checkin_days.contains(&day) {
self.checkin_days.push(day);
}
}
pub fn reset_daily(&mut self) {
self.is_checkin_today = false;
}
}