我已经为其中一个查询启用了查询缓存,当我运行测试或控制台应用程序时,它工作得很好(查询结果来自查询缓存,实体来自二级缓存)。但是,如果我通过WCF服务运行相同的查询,则永远不会命中缓存。
我还在两种情况下检查了日志,它们几乎完全相同,直到缓存未命中。
这是NH显示缓存放置的日志:
[25,4244] 16:15:18,237 DEBUG[NHibernate.Cache.StandardQueryCache]: caching query results in region: 'NHibernate.Cache.StandardQueryCache'; sql: <MyQuery>; parameters: <MyParameter>; first row: 0
[25,4244] 16:15:18,238 DEBUG[NHibernate.Caches.SysCache.SysCache]: adding new data: key=NHibernate-Cache:NHibernate.Cache.StandardQueryCache:sql: <MyQuery>; parameters: <MyParameter> ; first row: 0@-891130694&value=System.Collections.Generic.List`1[System.Object]
以下是NH的日志,显示缓存未命中:
[25,4244] 16:15:29,089 DEBUG[NHibernate.Cache.StandardQueryCache]: checking cached query results in region: 'NHibernate.Cache.StandardQueryCache'; sql: <MyQuery>; parameters: <MyParameter>; first row: 0
[25,4244] 16:15:29,089 DEBUG[NHibernate.Caches.SysCache.SysCache]: Fetching object 'NHibernate-Cache:NHibernate.Cache.StandardQueryCache:sql: <MyQuery>; parameters: <MyParameter>; first row: 0@519257116' from the cache.
[25,4244] 16:15:29,095 DEBUG[NHibernate.Cache.StandardQueryCache]: query results were not found in cache: sql: <MyQuery>; parameters: <MyParameter>; first row: 0
以下是NH的日志,显示缓存命中情况,不在WCF服务中时:
这是 NH 的日志,显示缓存是否命中,当不在 WCF 服务中时:
[11,3656] 17:37:48,718 DEBUG[NHibernate.Cache.StandardQueryCache]: checking cached query results in region: 'NHibernate.Cache.StandardQueryCache'; sql: <MyQuery>; parameters: <MyParameter>; first row: 0
[11,3656] 17:37:48,718 DEBUG[NHibernate.Caches.SysCache.SysCache]: Fetching object 'NHibernate-Cache:NHibernate.Cache.StandardQueryCache:sql: <MyQuery>; parameters: <MyParameter>; first row: 0@-369095952' from the cache.
[11,3656] 17:37:48,728 DEBUG[NHibernate.Cache.StandardQueryCache]: Checking query spaces for up-to-dateness <MyTableName>
[11,3656] 17:37:48,729 DEBUG[NHibernate.Caches.SysCache.SysCache]: Fetching object 'NHibernate-Cache:UpdateTimestampsCache:<MyTableName>@-1403193414' from the cache.
[11,3656] 17:37:48,729 DEBUG[NHibernate.Cache.StandardQueryCache]: returning cached query results for: sql: <MyQuery>; parameters: <MyParameter>; first row: 0
这是我用来执行查询的代码:
using (ISession session = SessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
IList<T> entities = session
.CreateCriteria(typeof(T))
.SetCacheable(true)
.Add(expression)
.List<T>();
transaction.Commit();
return entities;
}
为什么缓存没有被命中?