NHibernate 是一个流行的对象关系映射 (ORM) 框架,用于 .NET 应用程序,通过面向对象的代码实现无缝数据库交互。然而,当应用程序处理大量事务负载时,它们经常会因为频繁的数据库查询而遇到性能瓶颈。
为了解决这个问题,NHibernate 提供了二级缓存,它将对象保存在应用程序级别的内存中,从而减少了重复访问数据库的需要。 NCache是一种速度极快且可扩展的分布式缓存,可充当 NHibernate 二级缓存 提供程序,显著提高应用程序的速度、可扩展性和可靠性。
NCache 它为 NHibernate 提供高性能、分布式二级 (L2) 缓存,消除 .NET 应用程序中的数据库瓶颈。它提供线性可扩展性,通过对等集群实现 100% 正常运行时间,并且集成无需任何代码更改。
NCache 通过更快的查询、更少的数据库负载以及更高的可用性来提升 NHibernate,如下所述。
| 特性 | NHibernate L1(会话缓存) | NCache (分布式 L2 缓存) |
|---|---|---|
| 范围与隔离 | 事务范围。数据被隔离到单个事务中。 会话 目的。 | 进程级/集群级。数据在 Web 服务器集群中的所有会话和所有服务器之间共享。 |
| 数据持久化 | 临时对象。会话关闭或请求结束后,对象即被销毁。 | 持久化内存存储。数据独立于应用程序重启或会话关闭而保存在缓存集群中。 |
| 可扩展性 | 仅限进程内使用。受限于单个 Web 服务器的内存;无法在服务器集群中共享。 | 线性可扩展性。您可以动态添加缓存服务器来增加存储容量和吞吐量。 |
| 数据库同步 | 没有。L1 没有机制来知道其他进程是否更新了数据库。 | 自动同步。用途 SqlCache依赖项使用 Oracle 依赖项或轮询来使过期数据失效。 |
| 查询缓存 | 不适用(L1 主要用于基于 ID 的查找)。 | 已支持。缓存复杂查询的结果,避免重复执行代价高昂的 SQL 语句。 |
以下是一些主要特点 NCache 为 NHibernate 用户提供:
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true"
default-region-name="default"
key-case-sensitivity="false" >
<cache-regions>
<region name="AbsoluteExpirationRegion"
cache-name="demoCache"
priority="Default"
expiration-type="sliding"
expiration-period="180" />
<region name="default"
cache-name="demoCache"
priority="default"
expiration-type="none"
expiration-period="0"/>
</cache-regions>
</application-config>
</configuration>
<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="dependency.customer: [us]"/>
</database-dependencies>
</application-config>
</configuration>
此示例展示如何使用 NCache 存储和重用查询结果以提高性能。
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customer c")
.SetCacheable(true);
var customers = await query.ListAsync<Customer>();
var newCustomer = new Customer { Name = "John Doe" };
await session.SaveAsync(newCustomer);
await session.FlushAsync();
transaction.Commit();
}
}
Install-Package NHibernate.NCache
修改 NHibernate 配置文件以启用 NCache 作为二级缓存提供者。
更新 hibernate.cfg.xml
<hibernate-configuration xmlns="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>