项目简介
技术架构
项目结构

使用方法
配置
<cacheManager xmlns="http://cachemanager.michaco.net/schemas/CacheManagerCfg.xsd"><managers><cache name="cacheName" updateMode="Up" enableStatistics="false" enablePerformanceCounters="false"><handle name="handleName" ref="systemRuntimeHandle" expirationMode="Absolute" timeout="50s"/></cache></managers><cacheHandles><handleDef id="systemRuntimeHandle" type="CacheManager.SystemRuntimeCaching.MemoryCacheHandle`1, CacheManager.SystemRuntimeCaching"defaultExpirationMode="Sliding" defaultTimeout="5m"/></cacheHandles></cacheManager>声明
var cache = CacheFactory.Build<string>(s => s.WithDictionaryHandle());添加或者更新缓存
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 exceptionsif (!cache.TryUpdate("test", v => v, out string removedValue)) { Console.WriteLine("Value after remove is null?: {0}", removedValue == null); }缓存事件监听
private static void EventsExample() {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"); }计数器
private static void UpdateCounterTest() {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")); }Redis缓存
private static void RedisSample() {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"); }从Json读取配置
var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("cache.json");this.Configuration = builder.Build();项目地址:https://github.com/MichaCo/CacheManager