一 netcore中缓存相关的类库都在 Microsoft.Extensions.Caching ,使用MemoryCache首先安装包
Install-Package Microsoft.Extensions.Caching.Memory
using Microsoft.Extensions.Caching.Memory;
using System;
namespace 应用程序缓存2
{
class Program
{
static void Main(string[] args)
{
//缓存配置
MemoryCacheOptions options = new MemoryCacheOptions()
{
SizeLimit = 100,
CompactionPercentage = 0.2,
ExpirationScanFrequency = TimeSpan.FromSeconds(3)
};
//内存缓存
MemoryCache memoryCache = new MemoryCache(options);
while (true)
{
Console.Write("请输入要缓存的值:");
string result=Console.ReadLine();
//单个缓存项的配置
MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions()
{
//绝对过期时间
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),
//相对过期时间
//SlidingExpiration = TimeSpan.FromSeconds(3),
//优先级,当缓存压缩时会优先清除优先级低的缓存项
Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove
//缓存大小占1份
Size = 1
};
cacheEntityOps.RegisterPostEvictionCallback((key, value, reason, state) => {
Console.WriteLine($"回调函数输出【键:{key},值:{value},被清除的原因:{reason}】");
});
//检查是否存在Name的缓存
object cached;
bool res= memoryCache.TryGetValue("name",out cached);
if (!res)
{
Console.WriteLine("检查到不存在缓存");
memoryCache.Set("name", result, cacheEntityOps);
}
else
{
Console.WriteLine($"name缓存的结果是{cached}");
}
Console.ReadKey();
}
}
}
}