.net6怎么将数据写入缓存
在 .NET 6 中,可以使用 Microsoft.Extensions.Caching.Memory 命名空间中的 IMemoryCache 接口将数据写入内存缓存。IMemoryCache 是一个轻量级的内存缓存,适用于存储临时数据,以提高应用程序的性能。
以下是将数据写入缓存的步骤和示例代码:
1. 添加缓存服务到依赖注入容器
首先,需要在 Program.cs 文件中注册 IMemoryCache 服务,以便在应用程序中使用它。
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// 添加内存缓存服务
builder
.Services.AddMemoryCache();
var app = builder.Build();
app
.Run();
2. 注入 IMemoryCache 并写入数据
在需要使用缓存的地方,通过依赖注入获取 IMemoryCache 实例,并使用它来写入和读取数据。
示例代码
以下是一个简单的示例,展示如何在 ASP.NET Core Web API 中使用 IMemoryCache:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
[ApiController]
[Route("[controller]")]
public class CacheController : ControllerBase
{
private readonly IMemoryCache _cache;
public CacheController(IMemoryCache cache)
{
_cache
= cache;
}
[HttpGet("set")]
public IActionResult SetCache()
{
// 设置缓存数据
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) // 设置绝对过期时间
.SetSlidingExpiration(TimeSpan.FromMinutes(2)); // 设置滑动过期时间
_cache
.Set("key", "value", cacheEntryOptions);
return Ok("Data has been set in cache.");
}
[HttpGet("get")]
public IActionResult GetCache()
{
// 从缓存中读取数据
if (_cache.TryGetValue("key", out string value))
{
return Ok($"Value from cache: {value}");
}
else
{
return NotFound("Key not found in cache.");
}
}
}
3. 配置缓存选项
在设置缓存时,可以配置多种选项,例如过期时间、优先级等。以下是一些常用的缓存选项:
• 绝对过期时间(Absolute Expiration):指定缓存项的绝对过期时间。
• 滑动过期时间(Sliding Expiration):指定缓存项在最后一次访问后的过期时间。
• 优先级(Priority):指定缓存项的优先级,当内存不足时,低优先级的缓存项可能会被移除。
示例代码
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(5)) // 绝对过期时间
.SetSlidingExpiration(TimeSpan.FromMinutes(2)) // 滑动过期时间
.SetPriority(CacheItemPriority.Normal); // 设置优先级
_cache
.Set("key", "value", cacheEntryOptions);
4. 缓存回调和清理
可以为缓存项设置回调函数,在缓存项被移除时执行某些操作。例如,可以用于清理资源或记录日志。
示例代码
_cache.Set("key", "value", new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow
= TimeSpan.FromMinutes(5),
Size
= 1024, // 设置缓存项的大小
Priority
= CacheItemPriority.
Normal
}.RegisterPostEvictionCallback((key, value, reason, state) =>
{
// 缓存被移除时的回调函数
Console
.WriteLine($"Cache item {key} was removed due to {reason}.");
}));
5. 使用分布式缓存
如果需要在多个实例之间共享缓存数据,可以使用分布式缓存,如 Redis 或 SQL Server。以下是一个使用 Redis 作为分布式缓存的示例:
安装 Redis 缓存客户端
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
配置 Redis 缓存
在 Program.cs 文件中配置 Redis 缓存:
using Microsoft.Extensions.Caching.StackExchangeRedis;
var builder = WebApplication.CreateBuilder(args);
// 添加 Redis 分布式缓存
builder
.Services.AddStackExchangeRedisCache(options =>
{
options
.Configuration = "localhost:6379"; // Redis 服务器地址
options
.InstanceName = "SampleInstance";
});
var app = builder.Build();
app
.Run();
使用分布式缓存
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
[ApiController]
[Route("[controller]")]
public class CacheController : ControllerBase
{
private readonly IDistributedCache _cache;
public CacheController(IDistributedCache cache)
{
_cache
= cache;
}
[HttpGet("set")]
public async Task<IActionResult> SetCache()
{
// 设置缓存数据
var cacheEntryOptions = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) // 设置绝对过期时间
.SetSlidingExpiration(TimeSpan.FromMinutes(2)); // 设置滑动过期时间
await _cache.SetStringAsync("key", "value", cacheEntryOptions);
return Ok("Data has been set in cache.");
}
[HttpGet("get")]
public async Task<IActionResult> GetCache()
{
// 从缓存中读取数据
var value = await _cache.GetStringAsync("key");
if (value != null)
{
return Ok($"Value from cache: {value}");
}
else
{
return NotFound("Key not found in cache.");
}
}
}
总结
在 .NET 6 中,可以使用 IMemoryCache 接口将数据写入内存缓存,也可以使用分布式缓存(如 Redis)来实现跨实例的缓存共享。通过配置缓存选项,可以控制缓存的过期时间和优先级,并通过回调函数处理缓存项的移除事件。