二级缓存总是与会话工厂对象相关联。在运行事务时,它会在会话工厂级别加载对象,以便这些对象可用于整个应用程序,而不是绑定到单个用户。由于对象已经加载到缓存中,因此每当查询返回对象时,此时无需进行数据库事务。
二级缓存不仅要启用,而且要为您想要缓存的每个单独的实体类进行配置。所以启用缓存映射到 15 个表的所有 15 个对象。
在 XML 中,这是在元素内部完成的:
<cache usage="read-write"/>
在 Fluent NHibernate(非自动映射)中,它在 ClassMap 构造函数中或您放置其余映射代码的任何位置完成:
Cache.ReadWrite().Region("Configuration");
从这里开始取决于数据库的大小和负载,以及新数据必须如何呈现。
如果 Db 比较小并且写入很少
您可以在每次写入/更新时更新缓存。
ISession.Clear();
ReloadCache();
如果 Db 很大:
而且您每天可以奢侈地更新一次数据库,比如说凌晨 12 点,然后将“新”数据在缓存中保存一天,那么您也可以。在重新加载时,您将获得一些用户的延迟峰值。
这是一个例子:
http://www.codeproject.com/Articles/529016/NHibernate-Second-Level-Caching-Implementation
如果您的数据库很大并且用户必须获取更新的数据,您将不得不手动更新缓存中的数据。
Database db = new Database ();
Transaction tx = db.BeginTransaction ();
try
{
// Read from the cache
MyEntity1 entity1 = cache.Get <MyEntity1> ("pk of entity1");
// Cache is not read from the database
if (entity1 == null) entity1 = db.Get <MyEntity1> ("pk of entity1");
// Entity1 processing
updated = db.Update, (entity1); / / entity1 update saved to the database
if (updated) cache.Put (entity1); / / database update successfully, the update cache
// Transaction processing
tx.commit ();
}
catch
{
tx.Rollback ();
throw;
}
更多信息在这里:http://www.databaseskill.com/3093355/