我正在尝试设置 nhibernate 二级缓存我在这篇文章中看到, http://www.gitshah.com/2012/03/nhibernate-and-caching-part-2.html我想了解查询缓存和实体缓存之间的区别。它说你需要添加
Cache.ReadOnly(); or Cache.ReadWrite();
在每个实体映射上,如下所示:
public class CountryMap : ClassMap<country>
{
public CountryMap()
{
Table("dropdowns");
Id(x => x.Id, "pkey");
Map(x => x.Name, "ddlong");
Map(x => x.Code, "dddesc");
Where("ddtype = 'COUNTRY'");
//Informing NHibernate that the Country entity itself is cache-able.
Cache.ReadOnly();
}
}
但是当使用 nhibernate profiler 时,我看到有东西触及二级缓存,并且我没有设置这个 Cache.ReadOnly() 值。
真的需要这样吗?我是否应该对每个实体执行此操作(无论该实体多久更改一次?)。
如果答案是肯定的,我应该对所有实体执行此操作,我看到一个页面提到使用此行设置实体存在风险,因为如果您尝试加入,可能会导致 Select n + 1 查询问题该实体与查询中的其他实体。我正在使用 nhibernate profiler,看起来有些东西正在从下面的代码中命中二级缓存。在我的会话设置中,我有以下代码:
return configuration
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ApplicationMap>().Conventions.Add(typeof(Conventions)))
.ExposeConfiguration(
c => {
c.SetProperty("cache.provider_class", "NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache");
c.SetProperty("cache.use_second_level_cache", "true");
c.SetProperty("cache.use_query_cache", "true");
c.SetProperty("expiration", "86400");
})
.BuildSessionFactory();
我有一个通用的“查询”方法来执行此操作:
ICriteria c = Session.CreateCriteria(typeof(T));
c.SetCacheable(true);
return c.Future<T>().AsQueryable();
所以基本上我试图确认我是否正确设置了缓存,因为当我使用 nhibernate profiler 时看到一些二级缓存命中,但我没有在实体映射代码中设置缓存。我正在尝试确定是否需要做其他事情才能使缓存正常工作(或更好地工作)
当我使用 nhibernate profiler(没有在实体级别设置 Cache.ReadWrite())时,它似乎仍然命中了二级缓存。 (见下面的截图)