Sparkdo.Caching 3.0.0-preview.1

This is a prerelease version of Sparkdo.Caching.
dotnet add package Sparkdo.Caching --version 3.0.0-preview.1
                    
NuGet\Install-Package Sparkdo.Caching -Version 3.0.0-preview.1
                    
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="Sparkdo.Caching" Version="3.0.0-preview.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sparkdo.Caching" Version="3.0.0-preview.1" />
                    
Directory.Packages.props
<PackageReference Include="Sparkdo.Caching" />
                    
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 Sparkdo.Caching --version 3.0.0-preview.1
                    
#r "nuget: Sparkdo.Caching, 3.0.0-preview.1"
                    
#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 Sparkdo.Caching@3.0.0-preview.1
                    
#: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=Sparkdo.Caching&version=3.0.0-preview.1&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Sparkdo.Caching&version=3.0.0-preview.1&prerelease
                    
Install as a Cake Tool

Sparkdo.Caching

Sparkdo.Caching 是 Sparkdo Caching 的运行时包:基于 IDistributedCache 的 typed cache(DistributedCache<,>)、L1+L2 混合缓存(HybridCache<,>)、默认内存分布式 provider、SparkdoCachingOptions 集中配置、默认 key normalizer 与 AddSparkdoCaching() 一行接线。payload 序列化复用 Sparkdo.Json(source-generated、fail-closed、AOT 兼容)。

快速开始

// 1. 声明缓存项类型 + 注册进应用的 Sparkdo Json context
public sealed record UserCacheItem(string Name);

[SparkdoJsonContext]
[JsonSerializable(typeof(UserCacheItem))]
internal sealed partial class CacheJsonContext : JsonSerializerContext;

// 2. 接线
var services = new ServiceCollection();
services.AddSparkdoJson();               // 生成的聚合接线;AddSparkdoCaching 亦会兜底注册序列化栈
services.AddSparkdoCaching(options =>
{
    options.DefaultAbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
});

// 3. 解析使用
var provider = services.BuildServiceProvider();
var cache = provider.GetRequiredService<ICache<UserCacheItem>>();

await cache.SetAsync("42", new UserCacheItem("Ada"));
var user = await cache.GetAsync("42");                 // UserCacheItem? —— null 即未命中
var missing = await cache.GetAsync("no-such");         // null

var created = await cache.GetOrAddAsync("42", async ct =>
{
    return await LoadUserFromDatabaseAsync("42", ct);  // 缓存未命中时执行,结果自动写回缓存
});

不使用 DI 时可直接构造(与容器内注册的实现完全同型):

var options = Options.Create(new SparkdoCachingOptions());
ICache<UserCacheItem, string> cache = new DistributedCache<UserCacheItem, string>(
    new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())),
    new DefaultCacheKeyNormalizer(options),
    jsonSerializer,       // IJsonSerializer,如 new DefaultJsonSerializer(new JsonSerializationRuntime(...contributor))
    options);

IHybridCache<UserCacheItem, string> hybrid = new HybridCache<UserCacheItem, string>(
    distributedCache, new MemoryCache(Options.Create(new MemoryCacheOptions())),
    new DefaultCacheKeyNormalizer(options), jsonSerializer, options);

AddSparkdoCaching 注册了什么

services.AddSparkdoCaching();                 // 纯接线
services.AddSparkdoCaching(options => ...);   // 接线 + 追加默认 named options 配置
服务 默认实现 语义
IDistributedCache MemoryDistributedCache TryAdd singleton
ICacheKeyNormalizer DefaultCacheKeyNormalizer TryAdd singleton
IMemoryCache MemoryCache TryAdd singleton,全部 IHybridCache<> 共享
IJsonSerializer / JsonSerializationRuntime DefaultJsonSerializer(经 AddSparkdoJsonCore()) TryAdd,宿主先注册的实现优先
ICache<T> / ICache<T,TKey> DistributedCache<T> / DistributedCache<T,TKey> TryAdd 开放泛型 singleton
IHybridCache<T> / IHybridCache<T,TKey> HybridCache<T> / HybridCache<T,TKey> TryAdd 开放泛型 singleton

TryAdd 语义的含义:应用已注册的同形态服务(含闭合泛型精确注册,无论先后)在解析时优先;重复调用 AddSparkdoCaching() 幂等。与源生成器的 AddSparkdoJson() 调用顺序无关——JsonSerializationRuntime 在解析时聚合已注册的 contributor。

ICache:typed cache 逐方法

ICache<TCacheItem> 是 ICache<TCacheItem, string> 的字符串 key 别名;ICache<TCacheItem, TKey> 接受任意非空 key 类型(以 ToString() 进键规范化,结果不得为空白)。所有方法返回 ValueTask。

方法 行为
GetAsync(key) 未命中返回 null;底层字节反序列化为 null 时抛 InvalidOperationException(见「异常」)
TryGetAsync(key) 返回 CacheValue<T>,区分「不存在」(Missing)与「存在但不可用」(抛异常)两种语义
SetAsync(key, value) JSON UTF-8 序列化后写 L2;过期时间来自 SparkdoCachingOptions。另有 SetAsync(key, value, TimeSpan? absoluteExpirationRelativeToNow) 重载做调用级绝对过期覆盖(≤0 抛 ArgumentOutOfRangeException;其余条目选项仍取集中配置)
RemoveAsync(key) 移除规范化键
RemoveManyAsync(keys) 逐键规范化后并发移除(Task.WhenAll),空序列为 no-op
GetOrAddAsync(key, factory) 读缓存 → 未命中进入单飞创建 → 写回缓存并返回;相同 key 的并发调用合并为一次工厂执行

TryGetAsync 的典型用法:

var result = await cache.TryGetAsync("42");
if (result.HasValue)
{
    Use(result.Value);          // 存在时读取;Missing 状态读 .Value 会抛 InvalidOperationException
}

GetOrAddAsync 的工厂契约:

var value = await cache.GetOrAddAsync(
    "42",
    async ct =>                              // 以 CancellationToken.None 执行(见下)
    {
        var user = await database.Users.FindAsync(["42"], ct);
        return user ?? throw new InvalidOperationException("user not found"); // 不得返回 null
    });
  • 相同规范化 key 的并发调用合并为一次工厂执行(ConcurrentDictionary + Lazy<Task<T>>),所有等待者拿到同一结果;
  • 单飞内会再读一次缓存:竞态窗口内其他写入者已填充时,直接采用已存值、跳过工厂;
  • 工厂以 CancellationToken.None 执行:等待者的 token 只约束「自己等多久」(Task.WaitAsync),取消不会中断已共享的创建过程,也不会让其他等待者失败;
  • 工厂抛出的异常传播给所有并发等待者;返回 null 抛 ArgumentNullException;
  • 调用前 token 已取消时快速失败(OperationCanceledException),不会读缓存也不会调工厂。

IHybridCache:L1 + L2 混合缓存

IHybridCache<TCacheItem> 是 IHybridCache<TCacheItem, string> 的别名。本地内存(IMemoryCache)为 L1、IDistributedCache 为 L2:

方法 行为
GetOrCreateAsync(key, factory, options?) L1 命中直返(零序列化、零网络)→ 单飞内查 L2,命中则回填 L1 并返回 → 都未命中执行工厂并写入 L1+L2
SetAsync(key, value, options?) 写 L2(DistributedCacheEntryOptions)再写 L1(MemoryCacheEntryOptions);L2 写失败时异常上抛、L1 不被填充(避免本机脏读远端未确认的值)
RemoveAsync(key) 先移 L2 再移 L1
RemoveManyAsync(keys) L1 两段式清理(即时一次 + L2 删完补一次,防并发读回填旧值),L2 并发移除

读取的唯一入口是 GetOrCreateAsync——工厂兜底意味着调用方总有回退路径;纯直读请用 ICache。

每次调用的 HybridCacheEntryOptions(复用 Microsoft.Extensions.Caching.Abstractions 契约类型):

await hybrid.SetAsync(
    "42",
    user,
    new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(30),           // L2 分布式 TTL
        LocalCacheExpiration = TimeSpan.FromMinutes(5)   // L1 本地 TTL;缺省同 Expiration
    });
  • Expiration 未指定时回落 SparkdoCachingOptions 解析出的绝对过期;LocalCacheExpiration 未指定时同 Expiration(L1 不过期长于 L2);
  • 滑动过期只来自集中配置(HybridCacheEntryOptions 无此字段),L1 与 L2 同值;
  • 过期值 ≤ 0 一律在写入时抛 InvalidOperationException;
  • L1 键即规范化键(含缓存名),不同缓存项类型在同一 IMemoryCache 内天然隔离。

L1 是容器级共享的 IMemoryCache:N 种缓存项类型共用一个淘汰时钟,可用 services.Configure<MemoryCacheOptions>(...) 统一控制压缩与容量限制。

SparkdoCachingOptions 全解

services.AddSparkdoCaching();  // 之后随时可用标准 options 模式修改
services.Configure<SparkdoCachingOptions>(options =>
{
    // —— 全局属性 ——
    options.KeyPrefix = "tenant-a:";                          // 追加在业务 key 前(进键规范化)
    options.DefaultAbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30);
    options.DefaultSlidingExpiration = TimeSpan.FromMinutes(5);

    // —— 按类型配置(优先级高于按名配置)——
    options.ConfigureCacheName<UserCacheItem>("Accounts");    // 显式缓存名:优先级高于 attribute 与约定
    options.ConfigureCache<UserCacheItem>(cache =>
    {
        cache.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
        cache.SlidingExpiration = TimeSpan.FromMinutes(2);
    });

    // —— 按缓存名配置(无法引用缓存项类型时,如基础设施层)——
    options.ConfigureCache("Accounts", cache =>
    {
        cache.SlidingExpiration = TimeSpan.FromMinutes(1);
    });
});
成员 说明
KeyPrefix 公共键前缀,进入规范化键(默认空)
DefaultAbsoluteExpirationRelativeToNow 全局兜底绝对过期(默认 null = 不过期)
DefaultSlidingExpiration 全局兜底滑动过期(默认 null)
ConfigureCacheName<T>(name) 显式缓存名,优先级最高;空白名抛 ArgumentException
ConfigureCache<T>(configure) 按缓存项类型配置过期
ConfigureCache(name, configure) 按缓存名配置过期
GetCacheName<T>() 解析缓存名(见下)
GetCacheOptions<T>(name) 解析生效过期配置(扩展作者用)

缓存名解析顺序(缓存实例构造时解析一次并冻结;singleton 生命周期下运行期改配置不影响已构造实例):

  1. ConfigureCacheName<T> 显式配置;
  2. [CacheName("...")] attribute;
  3. 类型全名去掉 CacheItem 后缀(MyApp.UserCacheItem → MyApp.User;无后缀用全名)。

过期解析:按类型 → 按缓存名 → 全局默认逐层回落,未配置字段逐个回落(而非整块覆盖)。解析结果按 (类型, 缓存名) 缓存进 ConcurrentDictionary,Configure* 调用后失效重建;热路径读取零分配。两个语义细节:

  • 直接改 Default* 全局属性在组合首次解析后不再反映(与缓存名冻结同因);
  • GetCacheOptions<T> 返回的实例在调用间共享,调用方不得修改。

键格式

DefaultCacheKeyNormalizer(确定性纯映射,单次 string.Concat):

c:{缓存名},k:{SparkdoCachingOptions.KeyPrefix}{key.ToString()}

例:缓存名 Users、KeyPrefix = "tenant-a:"、key "42" → c:Users,k:tenant-a:42。自定义 TKey 需保证 ToString() 稳定且非空白(Guid、int 等直接可用)。整个键布局可通过替换 ICacheKeyNormalizer 改写。

序列化边界(重要)

payload 经注入的 IJsonSerializer(Sparkdo Json)的 UTF-8 出口(SerializeToUtf8Bytes / Deserialize(ReadOnlySpan<byte>))序列化,直接命中 System.Text.Json 源生成快路径。Sparkdo Json fail-closed:每个 payload 类型必须注册进应用的 [SparkdoJsonContext],否则首次序列化抛 JsonSerializerTypeNotRegisteredException:

[SparkdoJsonContext]
[JsonSerializable(typeof(UserCacheItem))]
internal sealed partial class CacheJsonContext : JsonSerializerContext;

// 宿主调用源生成器生成的 AddSparkdoJson()(聚合全部 context 为 contributor)。

这是设计而非缺陷:AOT / trimming 下没有反射兜底,未注册类型在编译期无从知晓,运行期宁可明确失败也不静默降级。整体替换序列化栈即可换 protobuf 等:预先注册自定义 IJsonSerializer 即可,此时 payload 不再要求进入 json context。

替换与扩展

// 替换底层分布式缓存(typed cache / 混合缓存接线自动跟随)
services.AddSingleton<IDistributedCache>(myProvider);

// 替换序列化栈
services.AddSingleton<IJsonSerializer>(mySerializer);

// 替换键规范化
services.AddSingleton<ICacheKeyNormalizer>(myNormalizer);

// 替换单个闭合泛型缓存(精确注册优先于开放泛型默认,与注册顺序无关)
services.AddSingleton<ICache<UserCacheItem>>(new PreWarmingUserCache(...));

// 统一控制 L1 淘汰与容量
services.Configure<MemoryCacheOptions>(options => options.SizeLimit = 10_000);

异常一览

异常 触发场景
InvalidOperationException 过期配置 ≤ 0(AbsoluteExpirationRelativeToNow / SlidingExpiration,含单次调用的 HybridCacheEntryOptions);底层字节反序列化结果不可赋给 TCacheItem(如其他写入方存了 JSON null——宁可失败也不把不可用值当 missing)
JsonSerializerTypeNotRegisteredException payload 类型未注册进任何 [SparkdoJsonContext](首次序列化时抛,消息含修复指引)
OperationCanceledException 传入已取消的 token:在访问缓存与工厂之前快速失败,工厂不会被调用
ArgumentNullException key / value / factory / keys 为 null;GetOrAddAsync / GetOrCreateAsync 工厂返回 null
ArgumentException key 为空白(含 TKey.ToString() 返回空白的自定义 key 类型);ConfigureCacheName / GetCacheOptions 的缓存名为空白

边界

  • 本包不依赖 Sparkdo 运行时,仅依赖 Sparkdo.Json 与 Sparkdo.Caching.Abstractions;AOT / trimming 分析器全绿。
  • 默认 provider 是进程内 MemoryDistributedCache——多实例部署需要共享缓存时切换 Redis(Sparkdo.Caching.Redis)或其他 IDistributedCache 实现。
  • 不支持 tags / 失效广播;失效是即时的单键操作,无跨实例通知。

验证

dotnet test src/caching/Sparkdo.Caching.slnx
dotnet pack  src/caching/Sparkdo.Caching.slnx -c Release
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.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (12)

Showing the top 5 NuGet packages that depend on Sparkdo.Caching:

Package Downloads
Sparkdo.Ddd.Domain

Sparkdo DDD 领域模型库,提供领域驱动设计的核心组件实现

Sparkdo.TenantManagement.Domain

Sparkdo 租户管理领域层,提供租户管理的核心业务逻辑和数据访问接口

Sparkdo.Caching.StackExchangeRedis

Sparkdo StackExchange.Redis 缓存库,提供基于 StackExchange.Redis 的分布式缓存功能实现

Sparkdo.SettingManagement.Domain

Sparkdo 设置管理领域库,提供设置管理功能的核心领域模型、仓储接口和业务逻辑实现

Sparkdo.PermissionManagement.Domain

Sparkdo 权限管理领域库,提供权限管理功能的核心领域模型、仓储接口和业务逻辑实现

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.0-preview.1 78 10/30/2026
2.0.0-preview.2 114 7/20/2026
2.0.0-preview.1 95 7/18/2026
1.0.4-preview.3 237 6/8/2026
1.0.4-preview.2 228 6/7/2026
1.0.4-preview.1 237 6/7/2026
1.0.3 605 6/6/2026
1.0.3-preview.1 230 5/17/2026
1.0.2 423 4/27/2026
1.0.2-preview.5 146 4/15/2026
1.0.2-preview.4 144 2/8/2026
1.0.2-preview.3 152 2/1/2026
1.0.2-preview.2 171 1/31/2026
1.0.2-preview.1 236 12/4/2025
1.0.1 1,107 11/27/2025
1.0.0 1,084 11/25/2025
1.0.0-preview.5 179 10/24/2025