protected TEntity GetItem <TEntity, TKey>(ICache cache, TKey key, CacheDomainOption <TEntity, TKey> option) { var cacheKey = option.GetCacheKey(key); var cacheItem = cache.Get <TEntity>(cacheKey); if (cacheItem == null) { //根据缓存名获取锁对象 object sync = GetSyncObject(option.GetCacheFullName()); lock (sync) { //再次从缓存读取 cacheItem = cache.Get <TEntity>(cacheKey); if (cacheItem == null) { //从原始数据读取 cacheItem = option.MissingItemHandler(key); if (!AbstractCache.IsDefault(cacheItem)) { OnSetCache(cache, cacheKey, cacheItem, option.SecondesToLive); } } } } return(cacheItem); }
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)); }