(文章目录)
前言
CacheManager 是用 C# 编写的 .NET 开源缓存抽象层。它支持各种缓存提供程序并实现许多高级功能。
CacheManager 包的主要目标是使开发人员更容易处理非常复杂的缓存方案。 使用CacheManager,只需几行代码即可实现多层缓存,例如分布式缓存前面的进程内缓存。
CacheManager不仅仅是一个为各种缓存提供程序统一编程模型的接口,这使得以后在项目中更改缓存策略变得非常容易。它还提供其他功能,如缓存同步、并发更新、序列化、事件、性能计数器...... 开发人员只能在需要时选择启用这些功能。
CacheManager的源码网址:https://github.com/MichaCo/CacheManager
一、基于CacheManager缓存中间件(通用版本)
1.安装包
CacheManager.SystemRuntimeCaching
2.添加或者更新缓存
using CacheManager.Core;
var cache = CacheFactory.Build<string>(s => s.WithDictionaryHandle());
Console.WriteLine("Testing update...");
if (!cache.TryUpdate("test", v => "item has not yet been added", out string newValue))
{
Console.WriteLine("Value not added?: {0}", newValue == null);
}
cache.Add("test", "start");
Console.WriteLine("Initial value: {0}", cache["test"]);
cache.AddOrUpdate("test", "adding again?", v => "updating and not adding");
Console.WriteLine("After AddOrUpdate: {0}", cache["test"]);
cache.Remove("test");
try
{
var removeValue = cache.Update("test", v => "updated?");
}
catch
{
Console.WriteLine("Error as expected because item didn't exist.");
}
// use try update to not deal with exceptions
if (!cache.TryUpdate("test", v => v, out string removedValue))
{
Console.WriteLine("Value after remove is null?: {0}", removedValue == null);
}
Console.ReadLine();
3.缓存事件监听
var cache = CacheFactory.Build<string>(s => s.WithDictionaryHandle());
cache.OnAdd += (sender, args) => Console.WriteLine("Added " + args.Key);
cache.OnGet += (sender, args) => Console.WriteLine("Got " + args.Key);
cache.OnRemove += (sender, args) => Console.WriteLine("Removed " + args.Key);
cache.Add("key", "value");
var val = cache.Get("key");
cache.Remove("key");
4.计数器
var cache = CacheFactory.Build<long>(s => s.WithDictionaryHandle());
Console.WriteLine("Testing update counter...");
cache.AddOrUpdate("counter", 0, v => v + 1);
Console.WriteLine("Initial value: {0}", cache.Get("counter"));
for (var i = 0; i < 12345; i++)
{
cache.Update("counter", v => v + 1);
}
Console.WriteLine("Final value: {0}", cache.Get("counter"));
二、基于CacheManager缓存中间件(FW版本)
1.Redis缓存
var cache = CacheFactory.Build<int>(settings =>
{
settings
.WithSystemRuntimeCacheHandle()
.And
.WithRedisConfiguration("redis", config =>
{
config.WithAllowAdmin()
.WithDatabase(0)
.WithEndpoint("localhost", 6379);
})
.WithMaxRetries(1000)
.WithRetryTimeout(100)
.WithRedisBackplane("redis")
.WithRedisCacheHandle("redis", true);
});
cache.Add("test", 123456);
cache.Update("test", p => p + 1);
var result = cache.Get("test");
2.读取json配置文件
var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
.AddJsonFile("cache.json");
this.Configuration = builder.Build();