代码地址:CSharp_DistributedCache_Simple
一、WinForm版(System.Runtime.Caching)
1、MemoryCache示例
2、引用Negut包
3、MemoryCacheHelper
查看代码
二、Web应用Net7版(框架内置)
1、MemoryCache示例
2、引用Negut包
using Microsoft.Extensions.Caching.Memory; // WebAPI框架自带
3、MemoryCache使用教程
(1)添加中间件(Program.cs)
使用builder.Services.AddMemoryCache();
进行添加
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMemoryCache(options => // 1、添加内存缓存中间件(一般用于粘性会话或单机缓存)
{
options.SizeLimit = 100; // 缓存的最大大小为100份
options.ExpirationScanFrequency = TimeSpan.FromSeconds(2); // 两秒钟查找一次过期项
options.CompactionPercentage = 0.2; // 缓存满了时候压缩20%的优先级较低的数据
options.TrackStatistics = false; // 设置是否跟踪内存缓存统计信息。 默认已禁用
options.TrackLinkedCacheEntries = false; // 设置是否跟踪链接条目。 默认已禁用
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
(2)Controller 控制器中使用(MemoryCacheController.cs)
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:MemoryCache WebAPI使用示例
*│ 作 者:执笔小白
*│ 版 本:1.0
*│ 创建时间:2023-7-20 19:02:56
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: MemoryCache_WebAPI.Controllers
*│ 类 名:MemoryCacheController
*└──────────────────────────────────────────────────────────────┘
*/
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace MemoryCache_WebAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class MemoryCacheController : ControllerBase
{
#region 变量
/// <summary>
/// 日志
/// </summary>
private readonly ILogger<MemoryCacheController> _logger;
/// <summary>
/// 内存缓存
/// </summary>
private readonly IMemoryCache _memoryCache;
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
#endregion 变量
/// <summary>
///
/// </summary>
public MemoryCacheController(ILogger<MemoryCacheController> logger, IMemoryCache memoryCache)
{
_logger = logger;
_memoryCache = memoryCache;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
#region 内存缓存 MemoryCache使用示例
#region 存值
string key1 = "myKey1",value1 = "Hello, World!1",
key2 = "myKey2",value2 = "Hello, World!2",
key3 = "myKey3",value3 = "Hello, World!3";
//方式一自定义规则:
MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(1)) // 设置一分钟后过期被清除-相对时间
.SetSlidingExpiration(TimeSpan.FromMinutes(1)) // 设置滑动过期时间;一分钟没有访问则清除
.SetSize(100) // 设置最大缓存项数量为100份
.SetPriority(CacheItemPriority.Normal); // 设置优先级为Normal
memoryCacheEntryOptions.RegisterPostEvictionCallback((keyInfo, valueInfo, reason, state) => // 缓存项过期被清除时的回调方法
{
Console.WriteLine($"回调函数输出【键:{keyInfo},值:{valueInfo},被清除;原因:{reason}】");
});
_memoryCache.Set(key1, value1, memoryCacheEntryOptions);
//方式二-相对时间_TimeSpan:
_memoryCache.Set(key2, value2, TimeSpan.FromMinutes(1)); // 设置一分钟后过期
//方式三-绝对时间_DateTimeOffset:
DateTimeOffset dateTimeOffset = new DateTimeOffset().AddMinutes(1); // 设置一分钟后过期
_memoryCache.Set(key3, value3, dateTimeOffset);
#endregion 存值
#region 取值
string retrievedValue = _memoryCache.Get<string>(key1) ?? string.Empty;
#endregion 取值
#region 检查值是否存在
bool isExist = _memoryCache.TryGetValue(key2, out string cache);
#endregion 检查值是否存在
#region 删除值
_memoryCache.Remove(key3);
#endregion 删除值
#endregion 内存缓存 MemoryCache使用示例
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}