这可能就像在棍子上要求月亮;但是有没有“C# 生产质量线程安全的内存中 LRU 缓存过期?或者有没有人有最佳实践的想法来实现同样的事情?
(LRU 是“最近最少使用”- http://en.wikipedia.org/wiki/Cache_algorithms#LRU)
澄清一下:我想在具有以下接口(interface)的 ASP.Net MVC 站点中支持内存缓存:
public interface ICache
{
T GetOrAdd<T>(string key, Func<T> create, TimeSpan timeToLive) where T : class;
bool Remove(string key);
}
- 我想要“GetOrAdd”,因为我希望这些操作是“原子的”——即避免两个线程同时尝试查询缓存的竞争条件
- 我想要 Create 函数,因为创建这些对象的成本很高(需要复杂的数据库访问)
- 我需要过期时间,因为这些对象会在一段时间后过期
Microsoft 的最佳解决方案似乎是“System.Runtime.Caching.MemoryCache”,但它似乎有几个警告:
- 它需要定期轮询缓存以遵守强加的内存限制。我的系统中不可能出现内存不足的情况。我读过这篇文章,这让我很担心:MemoryCache does not obey memory limits in configuration
- 它似乎只有“AddOrGetExisting”来支持我的接口(interface),它将构造的对象作为第二个参数——如果这个对象的创建成本很高,那么预先构造它不会有点破坏缓存点吗?
代码看起来像这样:
public sealed class Cache : ICache
{
private readonly MemoryCache _cache;
public Cache()
{
_cache = MemoryCache.Default;
}
public T GetOrAdd<T>(string key, Func<T> create, TimeSpan timeToLive) where T : class
{
// This call kinda defeats the point of the cache ?!?
var newValue = create();
return _cache.AddOrGetExisting(key, newValue, DateTimeOffset.UtcNow + timeToLive) as T;
}
public bool Remove(string key)
{
_cache.Remove(key);
return true;
}
}
或者 Lazy < T > 周围可能有更好的东西,它确实允许只创建一次结果,但感觉像是 hack(对缓存 Func 有影响吗?):
class Program
{
static void Main(string[] args)
{
Func<Foo> creation = () =>
{
// Some expensive thing
return new Foo();
};
Cache cache = new Cache();
// Result 1 and 2 are correctly the same instance. Result 3 is correctly a new instance...
var result1 = cache.GetOrAdd("myKey", creation, TimeSpan.FromMinutes(30));
var result2 = cache.GetOrAdd("myKey", creation, TimeSpan.FromMinutes(30));
var result3 = cache.GetOrAdd("myKey3", creation, TimeSpan.FromMinutes(30));
return;
}
}
public sealed class Foo
{
private static int Counter = 0;
private int Index = 0;
public Foo()
{
Index = ++Counter;
}
}
public sealed class Cache
{
private readonly MemoryCache _cache;
public Cache()
{
_cache = MemoryCache.Default;
}
public T GetOrAdd<T>(string key, Func<T> create, TimeSpan timeToLive) where T : class
{
var newValue = new Lazy<T>(create, LazyThreadSafetyMode.PublicationOnly);
var value = (Lazy<T>)_cache.AddOrGetExisting(key, newValue, DateTimeOffset.UtcNow + timeToLive);
return (value ?? newValue).Value;
}
public bool Remove(string key)
{
_cache.Remove(key);
return true;
}
}
其他想法:
- 我也找到了这个实现,但它不允许您指定基于时间的到期时间:Is it there any LRU implementation of IDictionary?
- 也许有一个使用 ReaderWriterLock 的实现?
- ConcurrentDictionary 的包装器?
最佳答案
我实现了一个线程安全的伪 LRU,专为并发工作负载而设计——目前正在生产系统中使用。性能非常接近 ConcurrentDictionary,比 MemoryCache 快 10 倍,命中率比传统的 LRU 更好。下面的 github 链接中提供了完整的分析。
用法看起来像这样:
int capacity = 666;
var lru = new ConcurrentTLru<int, SomeItem>(capacity, TimeSpan.FromMinutes(5));
var value = lru.GetOrAdd(1, (k) => new SomeItem(k));
bool removed = lru.TryRemove(1);
GitHub:https://github.com/bitfaster/BitFaster.Caching
Install-Package BitFaster.Caching
关于C# 生产质量线程安全内存 LRU 缓存过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30489854/