ThreatFlux/threatflux-threat-detection
GitHub: ThreatFlux/threatflux-threat-detection
一个基于 Rust 和 tokio 的异步优先缓存库,提供可插拔后端、多种淘汰策略和高级搜索功能。
Stars: 0 | Forks: 0
# ThreatFlux 缓存
一个灵活的、异步优先的 Rust 缓存库,支持可插拔的后端、多种淘汰策略以及高级搜索功能。
## 功能
- **异步优先设计**:基于 tokio 构建,实现高性能异步操作
- **泛型键值存储**:适用于任何可序列化的类型
- **多种后端**:
- 内存存储(默认)
- 文件系统持久化
- 易于添加自定义后端
- **淘汰策略**:
- LRU(最近最少使用)
- LFU(最不经常使用)
- FIFO(先进先出)
- TTL(存活时间)
- 仅手动
- **高级功能**:
- 条目元数据和自定义属性
- 搜索和查询功能
- 压缩支持
- 指标集成
- 自动持久化
- 条目统计和访问跟踪
## 安装说明
将以下内容添加到您的 `Cargo.toml` 中:
```
[dependencies]
threatflux-cache = "0.1.0"
```
### Feature Flags
- `default`:启用文件系统后端和 JSON 序列化
- `filesystem-backend`:文件系统存储支持
- `json-serialization`:JSON 格式支持
- `bincode-serialization`:Bincode 格式支持
- `compression`:对存储值的压缩支持
- `openapi`:OpenAPI schema 生成
- `metrics`:Prometheus 指标集成
- `tracing`:Tracing 支持
- `full`:启用所有功能
## 快速入门
### 基本用法
```
use threatflux_cache::prelude::*;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Clone)]
struct User {
id: u64,
name: String,
}
#[tokio::main]
async fn main() -> Result<(), Box> {
// Create a cache with default configuration
let cache: Cache = Cache::with_config(CacheConfig::default()).await?;
// Store a value
let user = User { id: 1, name: "Alice".to_string() };
cache.put("user:1".to_string(), user).await?;
// Retrieve a value
if let Some(user) = cache.get(&"user:1".to_string()).await? {
println!("Found user: {}", user.name);
}
Ok(())
}
```
### 使用文件系统持久化
```
use threatflux_cache::prelude::*;
let config = CacheConfig::default()
.with_persistence(PersistenceConfig::with_path("/tmp/my-cache"))
.with_eviction_policy(EvictionPolicy::Lru);
let backend = FilesystemBackend::new("/tmp/my-cache").await?;
let cache: Cache = Cache::new(config, backend).await?;
```
### 自定义元数据
```
use threatflux_cache::{CacheEntry, BasicMetadata};
let metadata = BasicMetadata {
execution_time_ms: Some(100),
size_bytes: Some(1024),
category: Some("api-response".to_string()),
tags: vec!["user".to_string(), "profile".to_string()],
};
let entry = CacheEntry::with_metadata(
"key".to_string(),
"value".to_string(),
metadata,
);
cache.add_entry(entry).await?;
```
### 搜索功能
```
use threatflux_cache::SearchQuery;
// Search by pattern and category
let query = SearchQuery::new()
.with_pattern("user")
.with_category("api-response")
.with_access_count_range(Some(5), None);
let results = cache.search(&query).await;
for entry in results {
println!("Found: {:?}", entry.value);
}
```
## 从 file-scanner 迁移
如果您正在从 file-scanner 的内置缓存进行迁移,请参阅 `examples/file_scanner_migration.rs` 获取完整的迁移指南。该库提供了 adapter pattern,可以在保持 API 兼容性的同时获得新缓存系统的好处。
## 配置选项
```
let config = CacheConfig::default()
// Capacity settings
.with_max_entries_per_key(100)
.with_max_total_entries(10_000)
// Eviction policy
.with_eviction_policy(EvictionPolicy::Lru)
// Persistence
.with_persistence(PersistenceConfig {
enabled: true,
path: Some("/var/cache/myapp".into()),
sync_interval: 100,
save_on_drop: true,
load_on_startup: true,
})
// TTL for all entries
.with_default_ttl(Duration::from_secs(3600))
// Enable compression
.with_compression(CompressionConfig {
algorithm: CompressionAlgorithm::Gzip,
level: 6,
min_size: 1024,
});
```
## 自定义存储后端
实现 `StorageBackend` trait 以创建自定义存储解决方案:
```
use async_trait::async_trait;
use threatflux_cache::{StorageBackend, CacheEntry, Result};
pub struct MyCustomBackend;
#[async_trait]
impl StorageBackend for MyCustomBackend {
type Key = String;
type Value = String;
type Metadata = ();
async fn save(&self, entries: &HashMap>>) -> Result<()> {
// Implementation
Ok(())
}
async fn load(&self) -> Result>>> {
// Implementation
Ok(HashMap::new())
}
// ... other required methods
}
```
## 性能考虑
- 缓存使用 `Arc>` 进行线程安全的并发访问
- 批量更新首选批量操作
- 文件系统后端的保存操作通过 semaphore 进行节流
- 考虑对大数值使用压缩以减少 I/O
## 许可证
根据以下任一许可证授权:
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
- MIT license ([LICENSE-MIT](LICENSE-MIT))
由您选择。
标签:可视化界面, 自定义请求头, 通知系统