Galosys.Foundation.FusionCache 26.5.15.1

dotnet add package Galosys.Foundation.FusionCache --version 26.5.15.1
                    
NuGet\Install-Package Galosys.Foundation.FusionCache -Version 26.5.15.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="Galosys.Foundation.FusionCache" Version="26.5.15.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Galosys.Foundation.FusionCache" Version="26.5.15.1" />
                    
Directory.Packages.props
<PackageReference Include="Galosys.Foundation.FusionCache" />
                    
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 Galosys.Foundation.FusionCache --version 26.5.15.1
                    
#r "nuget: Galosys.Foundation.FusionCache, 26.5.15.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 Galosys.Foundation.FusionCache@26.5.15.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=Galosys.Foundation.FusionCache&version=26.5.15.1
                    
Install as a Cake Addin
#tool nuget:?package=Galosys.Foundation.FusionCache&version=26.5.15.1
                    
Install as a Cake Tool

Galosys.Foundation.FusionCache

成熟度: 🟡 可用 — 功能完整,测试或文档可能不完善

FusionCache 集成模块,为 .NET 应用提供高性能、高可用的分布式缓存解决方案,支持故障安全、背板同步和多级缓存策略。

功能概览

1. 多级缓存

  • 内存缓存(L1)
  • 分布式缓存(L2,Redis)
  • 自动缓存降级
  • 缓存穿透保护

2. 故障安全机制

  • FailSafe 故障转移
  • 节流控制
  • 最大故障安全时间
  • 自动降级到内存缓存

3. 背板同步

  • Redis 背板支持
  • 多实例缓存同步
  • 实时缓存失效通知

4. 序列化支持

  • System.Text.Json 序列化
  • 自定义序列化器支持
  • 高性能序列化

安装

<PackageReference Include="Galosys.Foundation.FusionCache" Version="x.x.x" />

使用

注册服务

// 在 Startup.cs 或 Program.cs 中注册
services.AddFusionCache();

配置选项

services.AddFusionCache()
    .WithDefaultEntryOptions(opt =>
    {
        // 默认缓存持续时间
        opt.Duration = TimeSpan.FromMinutes(2);
        
        // 启用故障安全
        opt.IsFailSafeEnabled = true;
        
        // 故障安全节流时间
        opt.FailSafeThrottleDuration = TimeSpan.FromHours(2);
        
        // 最大故障安全时间
        opt.FailSafeMaxDuration = TimeSpan.FromMinutes(1);
    })
    .WithSerializer(new FusionCacheSystemTextJsonSerializer())
    .WithDistributedCache(sp => new RedisCache(new RedisCacheOptions 
    { 
        Configuration = connectionString 
    }))
    .WithBackplane(sp => new RedisBackplane(new RedisBackplaneOptions 
    { 
        Configuration = connectionString 
    }));

使用缓存

// 注入 IFusionCache
public class ProductService
{
    private readonly IFusionCache _cache;

    public ProductService(IFusionCache cache)
    {
        _cache = cache;
    }

    public async Task<Product> GetProductAsync(int id)
    {
        return await _cache.GetOrSetAsync<Product>(
            $"product:{id}",
            async ct => await LoadProductFromDbAsync(id, ct),
            options => options.SetDuration(TimeSpan.FromMinutes(10))
        );
    }

    public async Task UpdateProductAsync(Product product)
    {
        await SaveProductToDbAsync(product);
        await _cache.RemoveAsync($"product:{product.Id}");
    }
}

批量操作

// 批量获取
var products = await _cache.GetOrSetAllAsync<Product>(
    productIds.Select(id => $"product:{id}"),
    async (ids, ct) => await LoadProductsFromDbAsync(ids, ct),
    options => options.SetDuration(TimeSpan.FromMinutes(5))
);

// 批量移除
await _cache.RemoveAllAsync(
    productIds.Select(id => $"product:{id}")
);

自定义选项

// 使用自定义选项
var product = await _cache.GetOrSetAsync<Product>(
    $"product:{id}",
    async ct => await LoadProductFromDbAsync(id, ct),
    new FusionCacheEntryOptions
    {
        Duration = TimeSpan.FromMinutes(10),
        IsFailSafeEnabled = true,
        FailSafeMaxDuration = TimeSpan.FromHours(1),
        FailSafeThrottleDuration = TimeSpan.FromMinutes(5),
        FactorySoftTimeout = TimeSpan.FromMilliseconds(100),
        FactoryHardTimeout = TimeSpan.FromMilliseconds(500)
    }
);

核心类

分类 说明
模块 FusionCacheModule 服务注册与配置模块
序列化 FusionCacheSystemTextJsonSerializer System.Text.Json 序列化器
背板 RedisBackplane Redis 背板实现
缓存 RedisCache Redis 分布式缓存

配置说明

连接字符串配置

appsettings.json 中配置 Redis 连接字符串:

{
  "ConnectionStrings": {
    "Redis": "localhost:6379,password=your_password,defaultDatabase=0"
  }
}

缓存选项说明

选项 说明 默认值
Duration 缓存持续时间 2 分钟
IsFailSafeEnabled 启用故障安全 true
FailSafeThrottleDuration 故障安全节流时间 2 小时
FailSafeMaxDuration 最大故障安全时间 1 分钟
FactorySoftTimeout 工厂软超时 100ms
FactoryHardTimeout 工厂硬超时 500ms

故障安全机制

  1. 正常流程: 查询缓存 → 缓存命中 → 返回结果
  2. 缓存失效: 查询缓存 → 缓存过期 → 执行工厂方法 → 更新缓存 → 返回结果
  3. 故障安全: 查询缓存 → 缓存连接失败 → 返回过期数据 → 异步恢复缓存

依赖项

  • microsoft.extensions.caching.stackexchangeredis
  • ziggycreatures.fusioncache.backplane.stackexchangeredis
  • ziggycreatures.fusioncache.serialization.systemtextjson
  • Galosys.Foundation.Core

目录结构

Galosys.Foundation.FusionCache/
├── FusionCacheModule.cs
├── Galosys.Foundation.FusionCache.csproj
└── README.md

最佳实践

1. 缓存键命名

// 推荐使用冒号分隔的层级结构
var cacheKey = $"product:{id}";
var userCacheKey = $"user:{userId}:profile";
var listCacheKey = $"products:category:{categoryId}:page:{page}";

2. 缓存时间策略

// 热点数据:短时间缓存
options.SetDuration(TimeSpan.FromMinutes(5));

// 配置数据:长时间缓存
options.SetDuration(TimeSpan.FromHours(1));

// 静态数据:超长时间缓存
options.SetDuration(TimeSpan.FromDays(1));

3. 故障安全配置

// 关键业务:启用故障安全
options.IsFailSafeEnabled = true;
options.FailSafeMaxDuration = TimeSpan.FromHours(1);

// 非关键业务:禁用故障安全
options.IsFailSafeEnabled = false;

4. 序列化优化

// 使用 System.Text.Json(推荐)
options.Serializer = new FusionCacheSystemTextJsonSerializer();

// 自定义序列化选项
var jsonOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = false
};
options.Serializer = new FusionCacheSystemTextJsonSerializer(jsonOptions);

监控与调试

启用日志

services.AddLogging(builder =>
{
    builder.AddConsole();
    builder.SetMinimumLevel(LogLevel.Information);
});

性能指标

  • 缓存命中率
  • 缓存响应时间
  • 故障安全触发次数
  • 背板同步延迟

注意事项

  1. Redis 连接: 确保 Redis 服务器配置正确,网络可达
  2. 内存占用: 合理设置缓存时间,避免内存溢出
  3. 序列化: 大对象序列化可能影响性能,考虑使用压缩
  4. 并发控制: 高并发场景建议调整故障安全参数
  5. 版本兼容: 确保 FusionCache 版本与项目依赖兼容

示例项目

参考 samples/Dev.API 项目中的 FusionCache 集成示例。

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.5.15.1 23 5/15/2026
26.5.12.3 72 5/12/2026
26.5.12.2 75 5/12/2026
26.4.27.1-rc1 90 4/26/2026
26.4.25.1-rc1 88 4/25/2026
26.4.22.2-rc7 92 4/22/2026
26.4.22.2-rc6 89 4/22/2026
26.4.22.2-rc4 89 4/22/2026
26.4.22.2-rc3 86 4/22/2026
26.4.19.1-rc1 96 4/19/2026
26.4.12.8-rc1 90 4/12/2026
26.4.12.7-rc1 94 4/12/2026
26.4.12.5-rc1 85 4/12/2026
26.1.30.1-rc1 111 1/30/2026
26.1.29.1 119 1/29/2026
26.1.28.5 117 1/28/2026
26.1.28.4 108 1/28/2026
26.1.28.2 114 1/28/2026
26.1.23.6 110 1/23/2026
26.1.21.1 110 1/21/2026
Loading failed