NHibernate 是一种流行的 .NET 对象关系映射 (ORM) 解决方案。而且,它经常用于高事务环境中,在这些环境中,应用程序由于数据库和数据存储而面临性能和可扩展性瓶颈。
为了处理这个问题,NHibernate提供了两种类型的缓存,一级缓存(1st Level Cache)和二级缓存(2nd Level Cache)。一级缓存是内置的,并与用户的“会话对象”相关联,而二级缓存提供可插拔架构,并与“会话因素”级别(即应用程序级别)相关联。这意味着缓存不会受到用户会话进出的影响。您可以插入第三方缓存作为 NHibernate 二级缓存。
NCache 是适用于 .NET 应用程序的速度极快且可线性扩展的分布式缓存。 NCache 允许您添加更多缓存服务器来处理更大的事务负载。您可以插入 NCache 作为 NHibernate 二级缓存。
作为 NHibernate 二级缓存提供者架构的一部分, NCache 已经实施 ICacheProvider
和 ICacheinterfaces
. 结果,您可以配置 NCache 作为 NHibernate 二级缓存,无需任何编程,只需更改配置文件即可。
您只需修改您的 app.config
并指定 NCache 作为您的二级缓存提供程序并为其添加一个属性。您还可以在 app.config 中启用 NHibernate 的二级缓存和其他子缓存。这是一个例子 app.config
的变化:
<hibernate-configurationxmlns="urn:nhibernate-configuration-2.2">
...
<session-factory>
...
<property name="cache.provider_class">
Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider,
Alachisoft.NCache.Integrations.NHibernate.Cache
</property>
<property name="cache.use_second_level_cache">
true
</property>
...
</session-factory>
</hibernate-configuration>
<appSettings>
<add key="ncache.application_id"
value="myapp" />
</appSettings>
NCache 允许每个 NHibernate 区域使用其自己的属性进行不同的配置以缓存对象。以此目的 NCache 有一个名为的配置文件 NCacheNHibernate.xml
,其中包含 NHibernate 二级缓存使用的所有区域配置。以下是该配置文件的示例:
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true"
default-region-name="default"
key-case-sensitivity="false">
<cache-regions>
<region name="default"
cache-name="mycache"
priority="default"
expiration-type="none"
expiration-period="0" />
<region name="AbsoluteExpirationRegion"
cache-name="myRegioncache"
priority="Default"
expiration-type="sliding"
expiration-period="180" />
</cache-regions>
...
</application-config>
</configuration>
NCache 是一个强大的.NET分布式缓存,并提供了许多丰富的功能。这些功能之一是数据库同步,其中缓存跟踪数据库更改,如果数据库中相应的数据发生更改,则使缓存项无效或重新加载它。
您可以为 NHibernate 二级缓存提供程序配置 NCache 使用数据库同步。 只需修改 NCacheNHibernate.xml
配置文件如下:
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true"
default-region-name="default"
key-case-sensitivity="false">
...
<database-dependencies>
<dependency entity-name="nhibernator.BLL.Customer"
type="sql"
sql-statement="SELECT ContactName FROM dbo.Customers
WHERE CustomerID =?"
cache-key-format="depdency.customer:[pk]"/>
</database-dependencies>
</application-config>
</configuration>
NHibernate 提供了查询缓存功能,它将查询结果缓存在二级缓存中。您可以在以下位置启用 NHibernate 查询缓存: app.config
配置文件如下:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
...
<session-factory>
...
<property name="cache.use_query_cache">
true
</property>
...
</session-factory>
</hibernate-configuration>
查询与结果集的主键一起存储在名为的默认查询区域中 NHibernate.Cache.StandardQueryCache
。但是,作为查询结果检索到的对象被缓存到各自的区域。此外,启用查询缓存默认情况下不会缓存每个查询。相反,您必须在代码中将每个查询设置为可缓存,如下所示:
IQuery qry = session.CreateQuery("from Customer c").SetCacheable(true);
如果您的 NHibernate 应用程序在多服务器环境中运行,那么您需要分布式缓存,例如 NCache 作为 NHibernate 二级缓存提供者的原因如下: