在NHibernate中查询二级缓存

时间:2013-03-14 12:57:04

标签: .net nhibernate

设置

映射

我有一个MyItem类,它有一个由MyDetail项组成的延迟加载集合:

[Serializable]
class MyItem : IComparable, ICloneable
{
  public virtual int ID { get; set; }
}

[Serializable]
class MyDetail : ICloneable
{
  public virtual int ID { get; set; }
  public virtual MyItem EnclosingItem { get; set; }
}

void MyItemMap(IClassMapper<MyItem> ca)
{
  ca.Lazy(false);
  ca.Cache(cm => { cm.Usage(CacheUsage.NonstrictReadWrite); cm.Region(cacheRegion); });
  ca.Id(x => x.ID, cm => { cm.Generator(Generators.Native); });
  ca.Discriminator(cm => { cm.Column("Type"); cm.Type(NHibernateUtil.String); });
  ca.Bag(x => x.Details, cm =>
  {
    cm.Key(k => k.Column("ItemID"));
    cm.Inverse(true);
    cm.Type<DetailFactory>();
    cm.Cascade(Cascade.All | Cascade.DeleteOrphans);
    cm.Fetch(CollectionFetchMode.Select);
    cm.Lazy(CollectionLazy.Lazy);
    cm.Cache(m => { m.Usage(CacheUsage.NonstrictReadWrite); });
  } cr => cr.OneToMany());
}

void MyDetailMap(IClassMapper<MyDetail> ca)
{
  ca.Lazy(true);
  ca.Cache(cm => { cm.Usage(CacheUsage.NonstrictReadWrite); cm.Region(cacheRegion); });
  ca.Id(x => x.ID, cm => { cm.Generator(Generators.Native); });
  ca.ManyToOne(x => x.EnclosingItem, cm => { cm.Column("ItemID"); cm.NotNullable(true); cm.Fetch(FetchKind.Select); cm.Lazy(LazyRelation.Proxy); });
}

集合

加载相关MyDetail项的类是PersistentGenericBag:

class DetailList : PersistentGenericBag<MyDetail>
{
}

收集工厂

这通过自定义集合工厂发生:

class DetailFactory : IUserCollectionType
{
  public IPersistentCollection Instantiate(ISessionImplementor session, ICollectionPersister persister)
  {
    return new DetailList(session);
  }

  public IPersistentCollection Wrap(ISessionImplementor session, object collection)
  {
    return new DetailList(session, (IList<MyDetail>)collection);
  }
}

问题

假设我已经加载了一个MyItem,并且我至少要求一次详细信息,所以我的二级缓存(SLC)包含所有这些内容。还假设我只是主动使用1个细节,而实际上有100个细节连接到MyItem。这意味着每当我从SLC访问MyItem并访问我感兴趣的一个细节时,整个集合就会实现:

// Get item coming from SLC
MyItem myItem = nhSession.Get(id);

// Access detail, materializing all MyDetails from SLC
MyDetail myDetail = myItem.Details["Interesting"];

// Normally, this last line will invoke the default NH proxy
// which then materializes the Details collections, fetching
// all details belonging to myItem from the database, or from
// the SLC for that matter.
//
// To cater for my scenario, I've got access to an interceptor
// to do my own processing (the details to how this is hooked
// up are not very relevant). This interceptor should somehow
// be able to, instead of initializing the collection, return
// the result from the SLC rightaway. This would prevent
// the materialization of possibly large collections.

解决优化问题

现在我想通过绕过集合加载来优化这种情况,并直接查询SLC是否存在该细节。请注意,我的问题不是拦截代码中的实际细节调用,而是介入以什么方式返回的内容。

我正在使用SysCache,所以理论上我可以读出ASP.NET缓存,但由于缓存键是NH的实现细节,我不确定这是个好主意。

有人有指针吗?

1 个答案:

答案 0 :(得分:0)

我有这个工作,但净效果是我的应用程序现在甚至需要更长时间。由于这对我来说没有意义,我还在调查,但无论如何我都会发布代码。

首先我联系了一个听众。每次保存MyDetail时,它都会插入一个额外的映射。这意味着,除了在SLC中拥有MyDetail的ID之外,我还可以通过EnclosingItem.ID和MyDetail.Name来查找它们。

class PostLoadListener : IPostLoadEventListener
{
  public void OnPostLoad(PostLoadEvent @event)
  {
    // Only act when MyDetail is loaded
    var detail = @event.Entity as MyDetail;
    if (detail == null) return;

    ISessionImplementor session = @event.Session;
    var persister = @event.Persister;

    // Still tak into account caching settings (copied over these checks from NH)
    if (persister.HasCache == false || ((session.CacheMode & CacheMode.Put) != CacheMode.Put)) return;

    // Create the mapping by combining the collection ID and the detail
    // name, which together are being mapped to the actual detail ID
    var id = detail.EnclosingItem.ID + "#" + detail.Name;
    var cacheKey = new CacheKey(id, NHibernateUtil.String, PersistentContentDetailsList.IdMapRole, session.EntityMode, session.Factory);

    // Cache the mapping [detail.EnclosingItem.ID#detail.Name] => [detail.ID]
    persister.Cache.Put(cacheKey, detail.ID, session.Timestamp, null, null, true);
  }
}

然后,我确保我的DetailList在适用时执行上述查找:

class DetailList : PersistentGenericBag<MyDetail>
{
  public MyDetail this[string name]
  {
    get { MyDetail detail; TryGetValue(name, out detail); return detail; }
    set { /* */  }
  }

  private IList<ContentDetail> List { get { return this; }
  }

  /*
  * If the collection was already initialized, it doesn't make sense
  * to reach for the SLC, so skip it in that case. If it wasn't,
  * then try to fetch from the SLC. If the detail wasn't found there,
  * initialize the collection by triggering the enumerator and
  * subsequently find the detail by name.
  */
  public bool TryGetValue(string name, out MyDetail value)
  {
    return
      (value = WasInitialized
                 ? List.FirstOrDefault(i => i.Name == name)
                 : (GetCachedDetail(name) ?? List.FirstOrDefault(i => i.Name == name))
      ) != null;
  }

  /*
  * GetCachedDetail uses the collection identifier, combines it with
  * the detail name, and tries to find that mapping in the SLC.
  * If it exists, the ID is returned. So basically, you get to know
  * which MyDetail to fetch from the SLC when you know its EnclosingItem
  * and its name.
  */
  private ContentDetail GetCachedDetail(string name)
  {
    var mapId = Key + "#" + name;
    var persister = Session.Factory.GetEntityPersister(typeof(ContentDetail).FullName);
    var key = new CacheKey(mapId, NHibernateUtil.String, IdMapRole, Session.EntityMode, Session.Factory);
    var cacheEntry = persister.Cache.Get(key, Session.Timestamp);

    // This last step might be optimized by only executing the relevant 
    // loading statements of the Session.Load invocation chain
    return cacheEntry != null ? ((ISession)Session).Load<MyDetail>((int)cacheEntry) : null;
  }
}