Microsoft.Extensions.Caching.Memory
Microsoft.Extensions.Caching.Memory
是一个用于实现内存缓存的.NET库,它提供了本地内存缓存的实现,适合在单个服务器上运行的应用程序中使用。以下是关于如何使用 Microsoft.Extensions.Caching.Memory
的详细说明:1. 安装包
Microsoft.Extensions.Caching.Memory
包通常包含在 ASP.NET Core 项目中。如果你需要在其他类型的项目中使用它,可以通过 NuGet 安装:bash
dotnet add package Microsoft.Extensions.Caching.Memory
2. 配置缓存服务
在 ASP.NET Core 应用程序中,可以通过
Startup.cs
或 Program.cs
文件中的 IServiceCollection
来添加内存缓存服务:csharp
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
}
}
或者在 .NET 6+ 的顶级程序中:
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
3. 注入和使用 IMemoryCache
通过依赖注入获取
IMemoryCache
实例,并使用它来缓存数据。以下是一些常见的操作示例:设置缓存
csharp
public class CacheService
{
private readonly IMemoryCache _cache;
public CacheService(IMemoryCache cache)
{
_cache = cache;
}
public void SetCacheItem(string key, object value, TimeSpan expiration)
{
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(expiration);
_cache.Set(key, value, cacheEntryOptions);
}
}
获取缓存
csharp
public object GetCacheItem(string key)
{
if (_cache.TryGetValue(key, out object value))
{
return value;
}
return null;
}
创建或获取缓存(如果不存在)
csharp
public object GetOrCreateCacheItem(string key, Func<object> createItem, TimeSpan expiration)
{
return _cache.GetOrCreate(key, entry =>
{
entry.AbsoluteExpirationRelativeToNow = expiration;
return createItem();
});
}
4. 配置缓存大小限制
可以通过
MemoryCacheOptions
配置缓存大小限制:csharp
public class MyMemoryCache
{
public MemoryCache Cache { get; private set; }
public MyMemoryCache()
{
Cache = new MemoryCache(new MemoryCacheOptions
{
SizeLimit = 1024 // 设置缓存大小限制
});
}
}
5. 缓存过期策略
MemoryCache
支持多种过期策略,包括:-
绝对过期时间(Absolute Expiration):指定缓存项的绝对过期时间。
-
滑动过期时间(Sliding Expiration):如果缓存项在指定的时间间隔内未被访问,则过期。
-
优先级(Priority):当缓存空间不足时,根据优先级逐出缓存项。
6. 监听缓存项的逐出
可以为缓存项注册逐出回调,以便在缓存项被逐出时执行特定逻辑:
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(expiration)
.RegisterPostEvictionCallback((key, value, reason, state) =>
{
Console.WriteLine($"Cache item {key} was evicted for {reason}.");
});
7. 使用场景
Microsoft.Extensions.Caching.Memory
适用于以下场景:-
单服务器应用程序:在单个服务器上运行的应用程序中,内存缓存可以快速存储和检索数据。
-
临时数据缓存:缓存频繁访问但不经常变化的数据,以减少数据库或外部服务的访问次数。
总结
Microsoft.Extensions.Caching.Memory
提供了一个简单而强大的内存缓存解决方案,适用于 .NET 应用程序。通过依赖注入和灵活的配置选项,可以轻松地将内存缓存集成到应用程序中,从而提高性能和响应速度