如何查询缓存而不是实体?
场景:
- CustomerEntity 代表数据库中的 Customer 表。
- 有多个查询返回 CustomerEntities(列表和单个客户)
如何“伪造”(代理?)CustomerEntity,以便所有查询都尝试命中缓存的 CustomerEntities。显然,在每个查询中,我可以对每个单独的查询使用缓存旁路模式,但我想将它用于整个 Customer 表,而不管查询如何。
(缓存旁路)
private static readonly DataCache cache = CacheUtil.Instance.Cache;
public List<Customer> GetCustomers()
{
string cacheKey = "test";
var list = (List<Customer>)cache.Get(cacheKey);
if (list == null)
{
using (var context = DataObjectFactory.CreateContext())
{
var customers = context.Customer.Where(w => w.CustomerId > 10).ToList();
list = new List<Customer>();
foreach (var customer in customers)
list.Add(customer);
cache.Put(cacheKey, list);
return list;
}
}
else
{
return list;
}
}
The Scenario:
- CustomerEntity represents the Customer table in the database.
- There are several queries that return CustomerEntities (list and single customer)
How is it possible to "fake" (proxy?) the CustomerEntity so that all queries attempt to hit the cached CustomerEntities. Obviously, in each query I can use the cache-aside pattern, for each individual query, but I want to use it for the entire Customer table regardless of the query.
(Cache-aside)
private static readonly DataCache cache = CacheUtil.Instance.Cache;
public List<Customer> GetCustomers()
{
string cacheKey = "test";
var list = (List<Customer>)cache.Get(cacheKey);
if (list == null)
{
using (var context = DataObjectFactory.CreateContext())
{
var customers = context.Customer.Where(w => w.CustomerId > 10).ToList();
list = new List<Customer>();
foreach (var customer in customers)
list.Add(customer);
cache.Put(cacheKey, list);
return list;
}
}
else
{
return list;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这需要编写
IObjectSet
的自定义实现,它要么从缓存返回数据,要么查询真正的内部ObjectSet
。此实现的实例将在您的上下文中公开,而不是默认的ObjectSet
。另一种更简单的方法是简单地隐藏上下文并仅通过GetQuery()
等指定方法公开查询 - 所有查询都将使用此方法而不是context.Customer
因为 <他们将无法访问 code>context 。您还可以检查缓存上下文包装器。
That would require writting custom implementation of
IObjectSet<T>
which would either return data from cache or query the real internalObjectSet<T>
. Instances of this implementation will be exposed on your context instead of defaultObjectSet<T>
. Another and more simple approach is simply hiding your context and exposing queries only by specified method likeGetQuery()
- all your queries will use this method instead ofcontext.Customer
becausecontext
will be inaccessible for them.You can also check Caching context wrapper.