修改了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

+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 {