RuoVea.ExCache 10.0.0.2

dotnet add package RuoVea.ExCache --version 10.0.0.2
                    
NuGet\Install-Package RuoVea.ExCache -Version 10.0.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RuoVea.ExCache" Version="10.0.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RuoVea.ExCache" Version="10.0.0.2" />
                    
Directory.Packages.props
<PackageReference Include="RuoVea.ExCache" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RuoVea.ExCache --version 10.0.0.2
                    
#r "nuget: RuoVea.ExCache, 10.0.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RuoVea.ExCache@10.0.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RuoVea.ExCache&version=10.0.0.2
                    
Install as a Cake Addin
#tool nuget:?package=RuoVea.ExCache&version=10.0.0.2
                    
Install as a Cake Tool

📋 RuoVea.ExCache 组件概览

RuoVea.ExCache 是一个功能完整的缓存帮助类库,支持内存缓存和 Redis 缓存,提供统一的缓存操作接口。

🏗️ 核心架构

1. 缓存配置系统

配置文件结构
{
  "Cache": {
    "Prefix": "RuoVea",           // 缓存键前缀
    "CacheType": "MemoryCache",   // 缓存类型: MemoryCache、RedisCache
    "RedisConnectionString": "127.0.0.1:6379,password=,defaultDatabase=2"
  }
}
配置说明
  • Prefix: 所有缓存键的前缀,用于区分不同应用或环境
  • CacheType:
    • MemoryCache - 内存缓存,进程内缓存
    • RedisCache - Redis 分布式缓存
  • RedisConnectionString: Redis 连接字符串

🔧 核心功能接口

1. 智能读写方法

Cof_ReadWrite<T> - 读-写模式
T Cof_ReadWrite<T>(string key, Func<T> GetFun, TimeSpan timeSpanMin) where T : class

功能特点:

  • 先尝试从缓存读取
  • 如果缓存不存在,执行 GetFun 查询方法获取数据
  • 将查询结果写入缓存并设置过期时间
  • 返回缓存数据或新查询的数据

使用示例:

// 获取用户权限,如果缓存不存在则从数据库查询并缓存3小时
var permissions = CacheFactery.CaChe.Cof_ReadWrite<List<string>>(
    "permission_142307070910551", 
    () => { 
        return userService.GetPermissions(userId); 
    }, 
    new TimeSpan(3, 0, 0)  // 3小时有效期
);

2. 删除操作

单个/批量删除
// 同步删除
long Del(params string[] key)

// 异步删除  
Task<long> DelAsync(params string[] key)

使用示例:

// 删除单个键
cache.Del("user_123");

// 批量删除多个键
cache.Del("user_123", "user_456", "session_789");

// 异步删除
await cache.DelAsync("temp_data");
模式删除
Task<long> DelByProfixAsync(string pattern)

功能特点:

  • 根据键模式批量删除
  • 支持前缀匹配:pattern*
  • 支持包含匹配:*pattern*

使用示例:

// 删除所有以 "user_" 开头的缓存键
await cache.DelByProfixAsync("user_");

// 删除所有包含 "temp" 的缓存键  
await cache.DelByProfixAsync("*temp*");

3. 存在性检查

// 同步检查
bool Exists(string key)

// 异步检查
Task<bool> ExistsAsync(string key)

使用示例:

// 检查缓存是否存在
if (cache.Exists("user_profile_123")) 
{
    // 缓存存在,直接读取
    var profile = cache.Read<UserProfile>("user_profile_123");
}
else 
{
    // 缓存不存在,从数据源加载
    var profile = userService.GetProfile(123);
    cache.Write("user_profile_123", profile, TimeSpan.FromMinutes(30));
}

4. 读取操作

同步读取
// 读取为字符串
string Read(string key)

// 读取为指定类型
T Read<T>(string key)
异步读取
// 异步读取为字符串
Task<string> ReadAsync(string key)

// 异步读取为指定类型  
Task<T> ReadAsync<T>(string key)

支持的数据类型:

  • string - 字符串
  • byte[] - 字节数组
  • 数值类型 - int, long, double
  • 复杂对象 - 自定义类、集合等

使用示例:

// 读取字符串
string name = cache.Read<string>("user_name_123");

// 读取数值
int count = cache.Read<int>("online_users_count");

// 读取复杂对象
var user = cache.Read<User>("user_details_123");

// 读取字节数据
byte[] fileData = cache.Read<byte[]>("file_content_456");

// 异步读取
var settings = await cache.ReadAsync<AppSettings>("app_settings");

5. 写入操作

同步写入
// 永久缓存(取决于缓存策略)
bool Write(string key, object value)

// 带过期时间的缓存
bool Write(string key, object value, TimeSpan expire)
异步写入
// 异步永久缓存
Task<bool> WriteAsync(string key, object value)

// 异步带过期时间缓存  
Task<bool> WriteAsync(string key, object value, TimeSpan expire)

支持写入的数据类型:

  • string - 字符串
  • byte[] - 字节数组
  • 数值类型
  • 任何可序列化对象

使用示例:

// 永久缓存
cache.Write("app_version", "1.2.3");

// 带过期时间的缓存
cache.Write("session_123", sessionData, TimeSpan.FromMinutes(30));

// 缓存复杂对象
cache.Write("product_list", products, TimeSpan.FromHours(1));

// 异步写入
await cache.WriteAsync("recent_activities", activities, TimeSpan.FromMinutes(10));

🚀 完整使用示例

1. 基础使用

// 写入缓存
bool success = ExCache.CacheOptions.CaChe.Write("demo_key", "缓存值内容");

// 读取缓存
var value = ExCache.CacheOptions.CaChe.Read("demo_key");

// 检查是否存在
bool exists = ExCache.CacheOptions.CaChe.Exists("demo_key");

// 删除缓存
long deletedCount = ExCache.CacheOptions.CaChe.Del("demo_key");

2. 高级使用场景

用户会话管理
public class UserSessionService
{
    private readonly ICache _cache;
    
    public UserSessionService(ICache cache)
    {
        _cache = cache;
    }
    
    // 获取用户会话,如果不存在则创建
    public async Task<UserSession> GetOrCreateSessionAsync(long userId)
    {
        string cacheKey = $"user_session_{userId}";
        
        return await _cache.Cof_ReadWriteAsync(cacheKey, async () => 
        {
            // 缓存不存在时执行的逻辑
            var session = new UserSession 
            {
                UserId = userId,
                LoginTime = DateTime.Now,
                LastActivity = DateTime.Now
            };
            
            // 初始化会话数据...
            await InitializeSessionAsync(session);
            
            return session;
        }, TimeSpan.FromHours(2)); // 会话有效期2小时
    }
    
    // 更新用户会话活动
    public async Task UpdateSessionActivityAsync(long userId)
    {
        string cacheKey = $"user_session_{userId}";
        var session = await _cache.ReadAsync<UserSession>(cacheKey);
        
        if (session != null)
        {
            session.LastActivity = DateTime.Now;
            await _cache.WriteAsync(cacheKey, session, TimeSpan.FromHours(2));
        }
    }
    
    // 清除用户会话
    public async Task ClearUserSessionAsync(long userId)
    {
        await _cache.DelAsync($"user_session_{userId}");
    }
}
数据缓存策略
public class ProductService
{
    private readonly ICache _cache;
    
    public ProductService(ICache cache)
    {
        _cache = cache;
    }
    
    // 获取产品详情,带缓存
    public async Task<Product> GetProductDetailsAsync(long productId)
    {
        string cacheKey = $"product_details_{productId}";
        
        return await _cache.Cof_ReadWriteAsync(cacheKey, async () => 
        {
            // 从数据库获取产品详情
            var product = await _productRepository.GetByIdAsync(productId);
            
            // 加载关联数据
            await LoadProductRelationsAsync(product);
            
            return product;
        }, TimeSpan.FromMinutes(30)); // 产品数据缓存30分钟
    }
    
    // 当产品更新时清除缓存
    public async Task ClearProductCacheAsync(long productId)
    {
        await _cache.DelAsync($"product_details_{productId}");
        // 同时清除相关的列表缓存
        await _cache.DelByProfixAsync("product_list_*");
    }
}
防缓存击穿策略
public class SafeCacheService
{
    private readonly ICache _cache;
    private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks;
    
    public SafeCacheService(ICache cache)
    {
        _cache = cache;
        _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
    }
    
    // 安全的缓存获取,防止缓存击穿
    public async Task<T> GetSafeAsync<T>(string key, Func<Task<T>> factory, TimeSpan expiry) 
        where T : class
    {
        // 先尝试从缓存获取
        var cached = await _cache.ReadAsync<T>(key);
        if (cached != null) return cached;
        
        // 获取键对应的锁
        var lockObj = _locks.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
        
        await lockObj.WaitAsync();
        try
        {
            // 再次检查,防止并发时重复加载
            cached = await _cache.ReadAsync<T>(key);
            if (cached != null) return cached;
            
            // 执行工厂方法获取数据
            var data = await factory();
            
            // 写入缓存
            if (data != null)
            {
                await _cache.WriteAsync(key, data, expiry);
            }
            
            return data;
        }
        finally
        {
            lockObj.Release();
        }
    }
}

🎯 设计特点

1. 多缓存支持

  • MemoryCache: 进程内缓存,速度快
  • RedisCache: 分布式缓存,支持多实例共享

2. 统一接口

  • 同步和异步方法齐全
  • 泛型支持,类型安全
  • 统一的错误处理

3. 智能缓存策略

  • 读-写模式自动处理缓存逻辑
  • 灵活的过期时间设置
  • 批量删除和模式删除

4. 高性能

  • 异步操作支持
  • 连接池管理
  • 序列化优化

5. 易用性

  • 简单的配置方式
  • 直观的 API 设计
  • 丰富的使用示例

这个缓存组件为企业级应用提供了完整的缓存解决方案,既支持简单的键值缓存,也支持复杂的缓存策略和分布式缓存场景。

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on RuoVea.ExCache:

Package Downloads
RuoVea.ExSugar

Sqlsugar扩展 快速注入,支持简体中文、繁体中文、粤语、日语、法语、英语.使用方式:service.AddSqlsugar();继承RestFulLog 重写异常日志,操作日志,差异日志

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.0.2 199 1/26/2026
10.0.0.1 107 1/12/2026
10.0.0 537 7/25/2025
9.0.0.2 271 1/26/2026
9.0.0.1 119 1/12/2026
9.0.0 562 7/25/2025
8.0.1.2 625 1/26/2026
8.0.1.1 845 1/12/2026
8.0.1 5,591 4/23/2025
8.0.0 1,620 8/28/2024
7.0.1.2 651 1/26/2026
7.0.1.1 971 1/12/2026
7.0.1 6,663 4/23/2025
7.0.0 1,947 8/28/2024
6.0.6.2 777 1/26/2026
6.0.6.1 1,190 1/12/2026
6.0.6 8,576 4/23/2025
5.0.5.2 152 1/26/2026
5.0.5.1 147 1/12/2026
5.0.5 467 4/23/2025
Loading failed