使用ConcurrentDictionary实现轻量缓存

时间:2022-05-03 08:48:48

项目中需要用到一个轻量缓存,存储重复使用的数据。
在设计中需要考虑:
1.做成通用组件,为未来其他模块方法操作结果做准备。
2.缓存模块需要接口化,为未来替换使用外部缓存做准备。
3.使用默认缓存过期时间,单个Key的过期时间可以*配置。

使用ConcurrentDictionary来作为我们的缓存容器,并能保证线程安全。

     public interface IDataCache
{
TimeSpan Ttl
{
get;
} void Set(string key, object value); void Set(string key, object value, TimeSpan ttl); object Get(string key); void PurgeExpiredEntries();
}
     /// <summary>
/// An implementation of <see cref="IDataCache"/> which uses a dictionary to cache values in memory.
/// </summary>
public class InMemDataCache:IDataCache
{
private static readonly TimeSpan DefaultTtl = TimeSpan.FromMinutes(10); private readonly TimeSpan _ttl;
private readonly ConcurrentDictionary<string, CacheEntry> _cache = new ConcurrentDictionary<string, CacheEntry>(); /// <summary>
/// Initialize a new instance of <see cref="InMemDataCache"/> using the default TTL.
/// </summary>
public InMemDataCache()
: this(DefaultTtl)
{ } /// <summary>
/// Initialize a new instance of <see cref="InMemDataCache"/> using a specified TTL.
/// </summary>
/// <param name="ttl">
/// The time-to-live (TTL) of value saved into the cache. Zero or negative value indicates that values shall never expire.
/// </param>
public InMemDataCache(TimeSpan ttl)
{
_ttl = ttl;
} /// <summary>
/// The time-to-live (TTL) of value saved into the cache.
/// </summary>
public TimeSpan Ttl
{
get
{
return _ttl;
}
} /// <summary>
/// Save a key-value pair into the cache using the global TTL settings.
/// Existed value associated with the specified key shall be overwritten.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set(string key, object value)
{
Set(key, value, _ttl);
} /// <summary>
/// Save a key-value pair into the cache using the global TTL settings.
/// Existed value associated with the specified key shall be overwritten.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="ttl">
/// The time-to-live (TTL) of value saved into the cache. Zero or negative value indicates that values shall never expire.
/// </param>
public void Set(string key, object value, TimeSpan ttl)
{
var expirationTime = ttl <= TimeSpan.Zero ? DateTime.MinValue : DateTime.Now.Add(ttl);
var result = new CacheEntry(value, expirationTime);
_cache.AddOrUpdate(key, result, (k, o) => result);
} public object Get(string key)
{
CacheEntry entry;
if (!_cache.TryGetValue(key, out entry))
{
return null;
} if (entry.ExpirationTime == DateTime.MinValue || DateTime.Now < entry.ExpirationTime)
{
return entry.Value;
} CacheEntry old;
_cache.TryRemove(key, out old);
return null;
} public void PurgeExpiredEntries()
{
foreach (var key in _cache.Keys)
{
Get(key);
}
} private class CacheEntry
{
public readonly object Value;
public readonly DateTime ExpirationTime; public CacheEntry(object value, DateTime expirationTime)
{
// TODO: Complete member initialization
Value = value;
ExpirationTime = expirationTime;
}
}
}

完整demo路径:http://files.cnblogs.com/files/Nicolas-wang/Examples.Cache.zip