一个C#开发的非常实用的缓存中间件

今天给大家推荐一个C#开发的非常实用的缓存中间件,支持各种缓存。
在我们实际开发中,缓存是经常用到的。特别是一些需要重复执行且消耗资源的操作时,我们都会把结果存储在缓存中,下次需要用到直接从缓存读取。在.Net支持缓存方式,也是非常多,还有其他中间件比如Redis、Memcache,每一种缓存使用方法、接口都不一样,如果我们需要改变缓存策略的时候,就需要修改代码。
今天给大家推荐这个中间件,就可以很好的满足我们的需求。.

项目简介

这是一个用C#开发的.Net开源的缓存中间件,他支持各种缓存并提供了很多高级功能。它的主要目标是让开发人员开发更简单、特别是一些复杂的缓存场景。
项目支持多层缓存、分布式缓存、通过简单几行代码配置,就可以实现很多功能。提供了统一的缓存接口,方便项目改变缓存策略时,不需要大量的修改代码。而且项目还提供了很多功能,例如缓存同步、并发更新、序列化、事件、性能计数器。

技术架构

1、跨平台:这是基于.Net Core开发的系统,可以部署在Docker, Windows, Linux。
2、基于Net4.5开发。
3、支持缓存类别:MemoryCache、Redis 、Memcached 、Couchbase、System.Web.Caching。

项目结构

一个C#开发的非常实用的缓存中间件

使用方法

配置

<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