// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Runtime.Caching; using StackExchange.Redis; namespace DBCache.DAL { // for local cache the builtin .NET MemoryCache is used public class DAL_LocalCache : IDAL { private MemoryCache big_cache; private MemoryCache counter_cache; private IDAL real; public DAL_LocalCache(IDAL real) { this.real = real; big_cache = new MemoryCache("local_big_cache", new NameValueCollection()); counter_cache = new MemoryCache("local_counter_cache", new NameValueCollection()); } public Big GetBig(int id) { Big res = (Big)big_cache.Get(id.ToString(), null); if(res == null) { res = real.GetBig(id); big_cache.Set(id.ToString(), res, DateTimeOffset.MaxValue, null); } return res; } public int? GetCounter(String id) { int? res = (int?)counter_cache.Get(id, null); if(res == null) { res = real.GetCounter(id); counter_cache.Set(id, res, DateTimeOffset.MaxValue, null); } return res; } public void IncrementCounter(String id) { real.IncrementCounter(id); counter_cache.Set(id, real.GetCounter(id), DateTimeOffset.MaxValue, null); } public void Close() { big_cache.Dispose(); counter_cache.Dispose(); real.Close(); } } // for remote cache Redis is used public class DAL_RemoteCache : IDAL { private const int REMOTE_BIG_CACHE = 1; private const int REMOTE_COUNTER_CACHE = 2; private ConnectionMultiplexer con; private IDatabase big_cache; private IDatabase counter_cache; private IDAL real; // we need to serialize and deserialize - for production usage something more robust is needed private static string Big2String(Big o) { return o.Id + "," + o.Data1 + "," + o.Data2; } private static Big String2Big(string s) { if(s == null) return null; string[] parts = s.Split(','); return new Big { Id = int.Parse(parts[0]), Data1 = parts[1], Data2 = parts[2] }; } public DAL_RemoteCache(IDAL real) { this.real = real; con = ConnectionMultiplexer.Connect("localhost:6379"); big_cache = con.GetDatabase(REMOTE_BIG_CACHE); counter_cache = con.GetDatabase(REMOTE_COUNTER_CACHE); } public Big GetBig(int id) { Big res = String2Big((string)big_cache.StringGet(id.ToString())); if(res == null) { res = real.GetBig(id); big_cache.StringSet(id.ToString(), Big2String(res)); } return res; } public int? GetCounter(String id) { int? res = (int?)counter_cache.StringGet(id); if(res == null) { res = real.GetCounter(id); counter_cache.StringSet(id, res); } return res; } public void IncrementCounter(String id) { real.IncrementCounter(id); counter_cache.StringSet(id, real.GetCounter(id)); } public void Close() { real.Close(); } } }