Crate oxcache

Crate oxcache 

Source
Expand description

Copyright (c) 2025-2026, Kirky.X

MIT License

oxcache - 高性能多层缓存库

提供L1内存缓存和L2分布式缓存的两级缓存解决方案, 支持缓存降级、故障恢复和优雅关闭等功能。

The new API (v0.2.0+) provides a type-safe, independent cache interface:

use oxcache::Cache;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct User {
    id: u64,
    name: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Simple memory cache
    let cache: Cache<String, User> = Cache::new().await?;

    // Set a value
    let user = User { id: 1, name: "Alice".to_string() };
    cache.set(&"user:1".to_string(), &user).await?;

    // Get a value
    let user: Option<User> = cache.get(&"user:1".to_string()).await?;

    // Cache-aside pattern with fallback
    let user: User = cache.get_or(&"user:1".to_string(), || async {
        fetch_user_from_db(1).await
    }).await?;

    Ok(())
}

§Cache Types

§Memory Cache

let cache: Cache<String, MyType> = Cache::new().await?;
// or
let cache: Cache<String, MyType> = Cache::memory().await?;

§Redis Cache

let cache: Cache<String, MyType> = Cache::redis("redis://localhost:6379").await?;

§Tiered Cache (L1 + L2)

let cache: Cache<String, MyType> = Cache::tiered(10000, "redis://localhost:6379").await?;

§Advanced Configuration

use oxcache::{Cache, builder::BackendBuilder};
use std::time::Duration;

let cache: Cache<String, User> = Cache::builder()
    .backend(
        BackendBuilder::tiered()
            .l1_capacity(10000)
            .l2_connection_string("redis://localhost:6379")
            .auto_promote(true)
    )
    .ttl(Duration::from_secs(3600))
    .build()
    .await?;

§Key Types

The new API supports any type implementing CacheKey:

// String keys (default)
let cache: Cache<String, User> = Cache::new().await?;

// Numeric keys
let cache: Cache<u64, User> = Cache::new().await?;

// Custom key type
impl oxcache::traits::CacheKey for UserId {
    fn to_key_string(&self) -> String {
        format!("user:{}", self.0)
    }
}

let cache: Cache<UserId, User> = Cache::new().await?;

§Batch Operations

// Batch set
cache.set_many(vec![
    (&"key1".to_string(), &value1),
    (&"key2".to_string(), &value2),
]).await?;

// Batch get
let results: HashMap<String, User> = cache.get_many(vec![
    &"key1".to_string(),
    &"key2".to_string(),
]).await?;

// Batch delete
cache.delete_many(vec![
    &"key1".to_string(),
    &"key2".to_string(),
]).await?;

§Migration from Old API

If you’re using the old API (v0.1.x), see the migration guide:

The old API is deprecated but still functional. To migrate:

Old API:

let config = oxcache_config()
    .with_service("default", ServiceConfig::two_level())
    .build();
oxcache::init(config).await?;
let client = oxcache::get_client("default")?;

New API:

let cache: Cache<String, User> = Cache::tiered(10000, "redis://localhost:6379").await?;

§Features

  • l1-moka: Enable L1 memory cache (Moka)
  • l2-redis: Enable L2 distributed cache (Redis)
  • serialization: Enable JSON/Bincode serialization
  • metrics: Enable OpenTelemetry metrics
  • wal-recovery: Enable write-ahead log for recovery
  • batch-write: Enable optimized batch writes
  • full: Enable all features

§Example

use oxcache::Cache;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a tiered cache
    let cache: Cache<String, String> = Cache::tiered(
        10000,
        "redis://localhost:6379"
    ).await?;

    // Set and get
    cache.set(&"key".to_string(), &"value".to_string()).await?;
    let value = cache.get(&"key".to_string()).await?;

    println!("Got value: {:?}", value);
    Ok(())
}

Re-exports§

pub use client::CacheExt;
pub use client::CacheOps;
pub use config::legacy_config::CacheStrategy as LegacyCacheStrategy;
pub use config::legacy_config::DynamicConfig as LegacyDynamicConfig;
pub use config::Config;Deprecated
pub use config::CacheStrategy;
pub use config::CacheType;
pub use config::DynamicConfig;
pub use config::GlobalConfig;
pub use config::OxcacheConfig;
pub use config::OxcacheConfigBuilder;
pub use config::RedisMode;
pub use config::SerializationType;
pub use config::ServiceConfig;
pub use config::ConfigSource;
pub use config::LayerConfig;
pub use config::LegacyEvictionPolicy as EvictionPolicy;
pub use error::CacheError;
pub use error::Result;
pub use builder::BackendBuilder;
pub use builder::CacheBuilder;
pub use builder::TieredCacheBuilder;
pub use cache::Cache;
pub use traits::CacheKey;
pub use traits::Cacheable;
pub use backend::custom_tiered::AutoFixConfig;
pub use backend::custom_tiered::BackendType;
pub use backend::custom_tiered::ConfigFix;
pub use backend::custom_tiered::ConfigValidationResult;
pub use backend::custom_tiered::CustomTieredConfig;
pub use backend::custom_tiered::CustomTieredConfigBuilder;
pub use backend::custom_tiered::FixedConfigResult;
pub use backend::custom_tiered::Layer;
pub use backend::custom_tiered::LayerBackendConfig;
pub use backend::custom_tiered::LayerRestriction;
pub use sync::warmup::WarmupManager;
pub use sync::warmup::WarmupResult;
pub use sync::warmup::WarmupStatus;
pub use config::oxcache_config;
pub use config::L2Config;
pub use smart_strategy::CompressibilityChecker;
pub use smart_strategy::CompressionDecider;
pub use smart_strategy::HitRateCollector;
pub use smart_strategy::HitRateStats;
pub use smart_strategy::PrefetchDecider;
pub use smart_strategy::SmartStrategyConfig;
pub use smart_strategy::SmartStrategyManager;
pub use metrics::export_json_format;
pub use metrics::export_prometheus_format;
pub use metrics::get_enhanced_stats;
pub use metrics::CacheStats;
pub use http::CacheMiddlewareConfig;
pub use http::CacheMiddlewareState;
pub use http::HttpCacheAdapter;
pub use http::HttpCacheKeyGenerator;
pub use http::HttpCachePolicy;
pub use http::HttpCacheResponse;
pub use http::HttpRequest;

Modules§

backend
Copyright (c) 2025-2026, Kirky.X
bloom_filter
Copyright (c) 2025-2026, Kirky.X
builder
Copyright (c) 2025-2026, Kirky.X
cache
Copyright (c) 2025-2026, Kirky.X
client
Initialize cache configuration from a function.
config
Copyright (c) 2025-2026, Kirky.X
database
Copyright (c) 2025-2026, Kirky.X
error
Copyright (c) 2025-2026, Kirky.X
http
Copyright (c) 2025-2026, Kirky.X
macros
managerDeprecated
metrics
Copyright (c) 2025-2026, Kirky.X
rate_limiting
Copyright (c) 2025-2026, Kirky.X
recovery
Copyright (c) 2025-2026, Kirky.X
security
Copyright (c) 2025-2026, Kirky.X
serialization
Copyright (c) 2025-2026, Kirky.X
smart_strategy
Copyright (c) 2025-2026, Kirky.X
sync
Copyright (c) 2025-2026, Kirky.X
telemetry
Copyright (c) 2025-2026, Kirky.X
traits
Copyright (c) 2025-2026, Kirky.X
utils
Copyright (c) 2025-2026, Kirky.X

Macros§

add_feature_if_enabled
运行时检查特性是否启用(用于available_features等场景)
check_feature_dependence
编译时断言:检查特性依赖关系(支持full特性)
empty_async_fn
生成空的 Result 返回方法
empty_async_methods
为禁用的特性生成带有 async 方法的空实现
empty_struct
为禁用的特性生成空实现结构体及其基本实现
empty_struct_generic
为禁用的特性生成空实现结构体(带泛型参数)
empty_trait
为禁用的特性生成空 trait 定义
has_feature
检查是否启用了指定的功能特性
placeholder_module
为禁用功能的模块生成占位符模块声明
require_feature
编译时断言:确保功能依赖满足
secure_debug
安全记录调试级别日志
secure_info
安全日志宏 - 自动脱敏连接字符串

Structs§

KeyGenerator
缓存键生成器

Constants§

VERSION
oxcache 版本号

Functions§

get_all_feature_info
获取所有功能状态信息
get_l1_feature_info
获取 L1 缓存功能状态信息
get_l2_feature_info
获取 L2 缓存功能状态信息
is_l1_enabled
检查 L1 功能是否启用
is_l2_enabled
检查 L2 功能是否启用

Attribute Macros§

cached