Cache Pattern
a. Load All Data in Cache ( In order to save the over amount access for DB)
b. Load Data On Demand in Cache ( In order to save the over amount access for DB)
Key
Target Cache
Source DB Record
Solution
a.
// POCO
public class TRecord
{
field definition { get; set;}
}
public class CacheAllMgr
{
private static Dictionay<TKey, TRecord> _cacheRecord = new Dictionay<TKey, TRecord>();
private CacheAllMgr(); // Singleton
publc Dictionay<TKey, TRecord> GetAll()
{
if (_cacheRecord.Count == 0)
{
using (var context = new EF())
{
for(var item in context.DB)
{
_cacheRecord.Add(TKey, new TRecord { ... });
}
}
}
return _cacheRecord;
}
}
b.
public class CacheOnDemandMgr
{
private static Dictionay<TKey, TRecord> _cacheRecord = new Dictionay<TKey, TRecord>();
public TRecord FindRecordByKey(T key)
{
TRecord result = null
if (_cacheRecord.Keys.Contains(key)
{
return _cacheRecord[key];
}
else
{
using (var context = new EF())
{
var records = context.DB.Where(it=>it.key == key);
if (records.Count() > 0)
{
_cacheRecord.Add(key, new TRecord { field1 = records[0].field1 ... }); // load data from db into cache
result = _cacheRecord[key];
}
}
}
return result;
}
}
沒有留言:
張貼留言