protected IEnumerable <TEntity> GetItems <TEntity, TParam1, TParam2, TKey>(ICache cache, TParam1 param1, TParam2 param2, IEnumerable <TKey> keys, CacheDomainOption <TEntity, TParam1, TParam2, TKey> option) { //CacheKey 与属性键的映射(去重) IDictionary <string, TKey> keyDic = keys.Distinct().ToDictionary(key => option.GetCacheKey(param1, param2, key)); //访问缓存并获取不在缓存中的 CacheKey IEnumerable <string> missing; var cacheItems = cache.GetBatch <TEntity>(keyDic.Keys, out missing).ToList(); if (missing.Count() > 0) { //根据缓存名获取锁对象 object sync = GetSyncObject(option.GetCacheFullName()); lock (sync) { //二次查找缓存 IEnumerable <string> secondMissing; var secondCacheItems = cache.GetBatch <TEntity>(missing, out secondMissing).ToList(); cacheItems.AddRange(secondCacheItems); //从数据源获取 if (secondMissing.Count() > 0) { IEnumerable <TEntity> dbItems = option.GetMissingItems(param1, param2, secondMissing.Select(key => keyDic[key]).ToArray()); //过滤掉 null 项,并加入缓存 OnSetCacheBatch(cache, dbItems.Where(item => !AbstractCache.IsDefault(item)), key => option.GetCacheKey(param1, param2, option.EntityKeySelector(key)), option.SecondesToLive); cacheItems.AddRange(dbItems); } } } //按目标序列输出 return(cacheItems.OrderBy(entity => option.EntityKeySelector(entity), keys)); }
/// <summary> /// 将三键对象插入到缓存域,如果缓存域已存在该对象,则替换。 /// </summary> /// <param name="param1">要移除三键对象对应分组键参数一值。</param> /// <param name="param2">要移除三键对象对应分组键参数二值。</param> /// <param name="entity">要插入缓存域的三键对象。</param> public void SetItemToCache(TParam1 param1, TParam2 param2, TEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } Cache.Set(option.GetCacheKey(param1, param2, option.EntityKeySelector(entity)), entity); }