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); }
private CacheDomain(CacheDomainOption <TEntity> option) : base(option) { if (option.MissingItemHandler == null) { throw new ArgumentNullException("MissingItemHandler"); } this.option = option; }
internal AbstractCacheDomain(CacheDomainOption option) { cache = CacheManager.GetCacher(option.GetCacheFullName()); //使用缓存代理处理 if (option.ContextCacheEnabled && !(cache is AspnetCache)) { cache = new CacheProxy(cache); } }
private CacheDomain(CacheDomainOption <TEntity, TParam1, TParam2, TKey> option) : base(option) { if (option.EntityKeySelector == null) { throw new ArgumentNullException("EntityKeySelector"); } if (option.MissingItemHandler == null && option.MissingItemsHandler == null) { throw new ArgumentNullException("MissingItemHandler 与 MissingItemsHandler 至少有一个不能为 Null."); } this.option = option; }
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)); }