protected override void OnMiss(ICacheKey key, out object value) { var repository = new RepositoriesRepository(new PlatformDomainContext(), Logger); var keyById = key as RepositoryByIdCacheKey; if (keyById != null) { var repo = repository.GetByKey(keyById.Id); if (repo != null) { Add(key, repo); Add(new RepositoryByNameCacheKey(repo.Name), repo); value = repo; return; } } var keyByName = key as RepositoryByNameCacheKey; if (keyByName != null) { var repo = repository.GetByName(keyByName.Name); if (repo != null) { Add(key, repo); Add(new RepositoryByIdCacheKey(repo.Id), repo); value = repo; return; } } value = null; }
protected override void OnMiss(ICacheKey key, out object value) { var repository = new QueriesRepository(new PlatformDomainContext(), Logger); var byNameCacheKey = key as QueriesCacheStringKey; if (byNameCacheKey != null) { var query = repository.GetByName(byNameCacheKey.Name); if (query != null) { Add(key, query); Add(new QueriesCacheIntKey(query.Id), query); } value = query; return; } var byIdCacheCacheKey = key as QueriesCacheIntKey; if (byIdCacheCacheKey != null) { var query = repository.GetByKey(byIdCacheCacheKey.QueryId); if (query != null) { Add(key, query); Add(new QueriesCacheStringKey(query.Name), query); } value = query; return; } value = null; }
protected override void OnMiss(ICacheKey key, out object value) { base.OnMiss(key, out value); this.Add(key, key.KeyAsString); value = key.KeyAsString; MissCount++; }
/// <summary> /// Adds an object to the cache /// </summary> /// <param name="objectToCache">the object to cache</param> /// <param name="cacheKey">the key to cache it under</param> public void Add(object objectToCache, ICacheKey cacheKey) { if (Exists(cacheKey)) { Remove(cacheKey); } _globalCache.AddOrGetExisting(cacheKey.KeyHash(), objectToCache, _globalPolicy); }
public void TestTimeEvictionClearsIndex() { ICacheKey key = PutOneThingInCache(); _clock.SetDateTime(DateTime.Now.Add(TimeSpan.FromDays(5))); _cache.ClearOldEntries((long)TimeSpan.FromDays(4).TotalMilliseconds); Assert.IsFalse(_cache.HasKeySync(key)); Assert.IsFalse(_cache.HasKey(key)); }
/// <summary> /// Performs disk cache check synchronously. /// </summary> /// <returns> /// true if the key is found in disk cache else false. /// </returns> public bool DiskCheckSync(ICacheKey key) { if (ContainsSync(key)) { return(true); } return(CheckInStagingAreaAndFileCache(key)); }
private bool ShouldCache(ICacheKey key) { if (this.caches.ContainsKey(key.CacheName)) { return(this.Enabled && this.caches[key.CacheName] != CacheDuration.NotCached); } return(false); }
public CachingComponent(CacheAdapter cache, ICacheKey cacheKey, ConfigurationForType configurationForType) { _cache = cache; _cacheKey = cacheKey; _componentType = configurationForType.ComponentType; UniqueId = configurationForType.CachePerInstance ? Guid.NewGuid().ToString() : "Global"; }
/// <summary> /// Performs a key-value look up in the disk cache. If no value /// is found in the staging area, then disk cache checks are /// scheduled on a background thread. Any error manifests itself /// as a cache miss, i.e. the returned Task resolves to false. /// </summary> /// <param name="key">The cache key.</param> /// <returns> /// Task that resolves to true if an element is found, or false /// otherwise. /// </returns> public Task <bool> Contains(ICacheKey key) { if (ContainsSync(key)) { return(Task.FromResult(true)); } return(ContainsAsync(key)); }
/// <summary> /// Inserts a cache entry into the cache overwriting any existing cache entry. /// </summary> /// <param name="cacheKey">A unique identifier for the cache entry.</param> /// <param name="value">The object to insert.</param> /// <param name="cachePolicy">A <see cref="CachePolicy"/> that contains eviction details for the cache entry.</param> /// <returns></returns> public override bool Set(ICacheKey cacheKey, object value, ICachePolicy cachePolicy) { string key = GetKey(cacheKey); var item = new CacheItem(key, value); var policy = CreatePolicy(cacheKey, cachePolicy); MemoryCache.Default.Set(item, policy); return(true); }
public bool Contains(ICacheKey key) { if (this.Enabled) { return(this.cache[(CacheKey)key] != null); } return(false); }
internal EncodedMemoryCacheConsumer( IMemoryCache <ICacheKey, IPooledByteBuffer> memoryCache, IConsumer <EncodedImage> consumer, ICacheKey cacheKey) : base(consumer) { _memoryCache = memoryCache; _cacheKey = cacheKey; }
public TItem Get <TItem>(ICacheKey <TItem> key) where TItem : class { if (this._memoryCache.TryGetValue(key.CacheKey, out TItem value)) { return(value); } return(null); }
public FindTeamStubQueryHandler(IAuthenticatedUserAccessor authenticatedUserAccessor, ICache cache, ICacheKey cacheKey, IMongoCollection <Stub> stubsCollection, IMongoCollection <Team> teamsCollection) { _authenticatedUserAccessor = authenticatedUserAccessor; _cache = cache; _cacheKey = cacheKey; _stubsCollection = stubsCollection; _teamsCollection = teamsCollection; }
private void VerifyListenerOnWriteAttempt(ICacheKey key) { DuplicatingCacheEventListener listener = (DuplicatingCacheEventListener)_cacheEventListener; Assert.IsTrue(listener.GetEvents("OnWriteAttempt").Count != 0); SettableCacheEvent cacheEvent = (SettableCacheEvent)listener.GetLastEvent("OnWriteAttempt"); Assert.IsNotNull(cacheEvent); Assert.AreEqual(cacheEvent.CacheKey, key); }
/// <summary> /// Inserts a cache entry into the cache without overwriting any existing cache entry. /// </summary> /// <param name="cacheKey">A unique identifier for the cache entry.</param> /// <param name="value">The object to insert.</param> /// <param name="cachePolicy">An object that contains eviction details for the cache entry.</param> /// <returns> /// <c>true</c> if insertion succeeded, or <c>false</c> if there is an already an entry in the cache that has the same key as key. /// </returns> public override bool Add(ICacheKey cacheKey, object value, ICachePolicy cachePolicy) { string key = GetKey(cacheKey); var item = new CacheItem(key, value); var policy = CreatePolicy(cacheKey, cachePolicy); var existing = MemoryCache.Default.AddOrGetExisting(item, policy); return(existing.Value == null); }
public CacheInterceptor(CacheAdapter cache, ICacheKey cacheKey, ILockObjectGenerator lockObjectGenerator, ConfigurationForType configurationForType) { _cache = cache; _cacheKey = cacheKey; _lockObjectGenerator = lockObjectGenerator; _configurationForType = configurationForType; }
public void TestGetResourceWithoutAwaitingIndex() { ICacheKey key = PutOneThingInCache(); // A new cache object in the same directory. Equivalent to a process restart. // Index may not yet updated. DiskStorageCache cache2 = CreateDiskCache(_storage, false); Assert.IsNotNull(cache2.GetResource(key)); }
protected RedisTransactionAction(eRedisTransactionActionType ActionType, ICacheKey Key) { this.ActionType = ActionType; if (Key == null) { throw new ArgumentNullException("parameter key cannot be null"); } this.Key = Key; this.Properties = new Dictionary <string, object>(); }
private void Reset() { _cacheKey = null; _resourceId = null; _itemSize = 0; _cacheLimit = 0; _cacheSize = 0; _exception = null; _evictionReason = EvictionReason.NONE; }
private Task <EncodedImage> GetAsync(ICacheKey key, AtomicBoolean isCancelled) { try { if (isCancelled.Value) { throw new OperationCanceledException(); } EncodedImage result = _stagingArea.Get(key); if (result != null) { Debug.WriteLine($"Found image for { key.ToString() } in staging area"); _imageCacheStatsTracker.OnStagingAreaHit(); } else { Debug.WriteLine($"Did not find image for { key.ToString() } in staging area"); _imageCacheStatsTracker.OnStagingAreaMiss(); try { IPooledByteBuffer buffer = ReadFromDiskCache(key); if (buffer == null) { return(Task.FromResult(default(EncodedImage))); } CloseableReference <IPooledByteBuffer> reference = CloseableReference <IPooledByteBuffer> .of(buffer); try { result = new EncodedImage(reference); } finally { CloseableReference <IPooledByteBuffer> .CloseSafely(reference); } } catch (Exception) { return(Task.FromResult(default(EncodedImage))); } } return(Task.FromResult(result)); } catch (Exception) { // Log failure // TODO: 3697790 Debug.WriteLine($"Failed to schedule disk-cache read for { key.ToString() }"); throw; } }
/// <summary> /// Inserts resource into file with key. /// </summary> /// <param name="key">Cache key.</param> /// <param name="callback"> /// Callback that writes to an output stream. /// </param> /// <returns>A sequence of bytes.</returns> public IBinaryResource Insert(ICacheKey key, IWriterCallback callback) { // Write to a temp file, then move it into place. // This allows more parallelism when writing files. SettableCacheEvent cacheEvent = SettableCacheEvent.Obtain().SetCacheKey(key); _cacheEventListener.OnWriteAttempt(cacheEvent); string resourceId; lock (_lock) { // For multiple resource ids associated with the same image, // we only write one file resourceId = CacheKeyUtil.GetFirstResourceId(key); } cacheEvent.SetResourceId(resourceId); try { // Getting the file is synchronized IInserter inserter = StartInsert(resourceId, key); try { inserter.WriteData(callback, key); // Committing the file is synchronized IBinaryResource resource = EndInsert(inserter, key, resourceId); cacheEvent.SetItemSize(resource.GetSize()) .SetCacheSize(_cacheStats.Size); _cacheEventListener.OnWriteSuccess(cacheEvent); return(resource); } finally { if (!inserter.CleanUp()) { Debug.WriteLine("Failed to delete temp file"); } } } catch (IOException ioe) { cacheEvent.SetException(ioe); _cacheEventListener.OnWriteException(cacheEvent); Debug.WriteLine("Failed inserting a file into the cache"); throw; } finally { cacheEvent.Recycle(); } }
private void VerifyListenerOnReadException(ICacheKey key, IOException exception) { DuplicatingCacheEventListener listener = (DuplicatingCacheEventListener)_cacheEventListener; Assert.IsTrue(listener.GetEvents("OnReadException").Count != 0); SettableCacheEvent cacheEvent = (SettableCacheEvent)listener.GetLastEvent("OnReadException"); Assert.IsNotNull(cacheEvent); Assert.AreEqual(cacheEvent.CacheKey, key); Assert.IsNotNull(cacheEvent.Exception); }
private void VerifyListenerOnHit(ICacheKey key, string resourceId) { DuplicatingCacheEventListener listener = (DuplicatingCacheEventListener)_cacheEventListener; Assert.IsTrue(listener.GetEvents("OnHit").Count != 0); SettableCacheEvent cacheEvent = (SettableCacheEvent)listener.GetLastEvent("OnHit"); Assert.IsNotNull(cacheEvent); Assert.AreEqual(cacheEvent.CacheKey, key); Assert.AreEqual(cacheEvent.ResourceId, resourceId); }
public void TestHasKeyWithPopulateAtStartupWithoutAwaitingIndex() { ICacheKey key = PutOneThingInCache(); // A new cache object in the same directory. Equivalent to a process restart. // Index may not yet updated. DiskStorageCache cache2 = CreateDiskCache(_storage, true); Assert.IsTrue(cache2.HasKey(key)); Assert.IsTrue(cache2.HasKeySync(key)); }
/// <summary> /// Adds an object to the cache /// </summary> /// <param name="objectToCache">the object to cache</param> /// <param name="cacheKey">the key to cache it under</param> public virtual void Add <T>(object objectToCache, ICacheKey cacheKey) { if (Exists(cacheKey)) { Remove <T>(cacheKey); } AddKey(cacheKey.ValueType, cacheKey); _globalCache.Set(cacheKey.KeyHash(), objectToCache); }
/// <summary> /// Performs key-value look up in disk cache. If value is not /// found in disk cache staging area then disk cache read is /// scheduled on background thread. /// Any error manifests itself as cache miss, i.e. the returned /// task resolves to null. /// </summary> /// <param name="key">The cache key.</param> /// <param name="isCancelled">The cancellation flag.</param> /// <returns> /// Task that resolves to cached element or null if one cannot /// be retrieved; returned task never rethrows any exception. /// </returns> public Task <EncodedImage> Get(ICacheKey key, AtomicBoolean isCancelled) { EncodedImage pinnedImage = _stagingArea.Get(key); if (pinnedImage != null) { return(FoundPinnedImage(key, pinnedImage)); } return(GetAsync(key, isCancelled)); }
/// <summary> /// Remove an entity from this /// </summary> /// <param name="birthMark">the entity's birthmark to remove</param> /// <returns>success status</returns> public bool Remove(ICacheKey cacheKey) { LiveCacheKey newKey = (LiveCacheKey)cacheKey; if (!Birthmarks[genericCollectionLabel].Any(mark => mark.KeyHash().Equals(newKey.KeyHash()))) { return(false); } return(Birthmarks[genericCollectionLabel].RemoveWhere(key => key.BirthMark == newKey.BirthMark) > 0); }
public async Task <TItem> GetAsync <TItem>(ICacheKey cachekey) where TItem : class { string itemJson = await this.GetStringAsync(cachekey); if (string.IsNullOrEmpty(itemJson)) { return(null); } return(JsonConvert.DeserializeObject <TItem>(itemJson)); }
public async Task <string> GetStringAsync(ICacheKey cachekey) { string item = await this._cache.GetStringAsync(cachekey.Key); if (string.IsNullOrEmpty(item)) { return(string.Empty); } return(item); }
public CachedPostprocessorConsumer( IConsumer <CloseableReference <CloseableImage> > consumer, ICacheKey cacheKey, bool isRepeatedProcessor, IMemoryCache <ICacheKey, CloseableImage> memoryCache) : base(consumer) { _cacheKey = cacheKey; _isRepeatedProcessor = isRepeatedProcessor; _memoryCache = memoryCache; }
public async Task AddAsync <TItem>(ICacheKey cachekey, TItem item) { if (item == null) { return; } string itemJson = JsonConvert.SerializeObject(item); await this.AddStringAsync(cachekey, itemJson); }
/// <summary> /// Returns whether the image is stored in the disk cache. /// </summary> /// <param name="imageRequest"> /// The imageRequest for the image to be looked up. /// </param> /// <returns> /// true if the image was found in the disk cache, /// false otherwise. /// </returns> public async Task <bool> IsInDiskCacheAsync(ImageRequest imageRequest) { ICacheKey cacheKey = _cacheKeyFactory.GetEncodedCacheKey(imageRequest, null); bool found = await _mainBufferedDiskCache.Contains(cacheKey).ConfigureAwait(false); if (!found) { return(await _smallImageBufferedDiskCache.Contains(cacheKey).ConfigureAwait(false)); } return(found); }
protected override void OnMiss(ICacheKey key, out object value) { var repo = new TablesRepository(new PlatformDomainContext(), Logger); var table = repo.AdHocQuery().AsNoTracking().Include(e => e.Columns).SingleOrDefault(e => e.Id == ((TableCacheKey) key).Id); if (table != null) { this.Add(key, table); } value = table; }
public void Add(ICacheKey key, object value) { if (this.ShouldCache(key)) { if (this.caches.ContainsKey(key.CacheName)) { this.Add(key, value, this.caches[key.CacheName]); } else { this.Add(key, value, CacheDuration.Permanent); } } }
protected override void OnMiss(ICacheKey key, out object value) { var codeKey = (SystemParametersCacheKey)key; var code = codeKey.KeyAsString; var domainContext = new SystemParametersDomainContext(); var sp = domainContext.SystemParameters.Find(code); if (sp != null) { Add(key, sp); value = sp; return; } value = null; }
public object this[ICacheKey key] { get { if (this.Enabled) { if (this.Contains(key)) { return this.cache[(CacheKey)key]; } return null; } return null; } }
protected object Get(ICacheKey key) { try { _lock.EnterUpgradeableReadLock(); object value; if(cache.TryGetValue(key.GetStringKey(), out value)) { return value; } OnMiss(key, out value); var cacheKey = BuildUniqueStringKey(key); var opts = new MemoryCacheEntryOptions(); if (_useAbsoluteExpiration) { opts.AbsoluteExpiration = AbsoluteExpiration; } else if (_useSlidingExpiration) { opts.SlidingExpiration = SlidingExpirationSpan; } cache.Set(key.GetStringKey(), value, opts); return value; } finally { if(_lock.IsUpgradeableReadLockHeld) { _lock.ExitUpgradeableReadLock(); } } }
private void GetFromCacheOrRun(IInvocation invocation, ICacheKey ck) { object result = null; lock (_lock) { CompositeKey key = CalculateKey(invocation, (ck != null && ck.KeyAttributes != null && ck.KeyAttributes.Length > 0)?ck.KeyAttributes:null); if (Cache.TryGet(key.FullKey, out result,invocation.Method.ReturnType)) invocation.ReturnValue = result; else { base.PerformProceed(invocation); if (invocation.ReturnValue != null) Cache.Add(key.FullKey, invocation.ReturnValue, invocation.Method.ReturnType); else { if (!ck.UseExactMatch) if (Cache.TryGet(key.MinimalKey, out result, invocation.Method.ReturnType, ck.UseExactMatch)) invocation.ReturnValue = result; } } } }
private string BuildUniqueStringKey(ICacheKey key) { return String.Format("{0};{1};{2}", GetType().FullName, key.GetType().FullName, key.GetStringKey()); }
protected object Remove(ICacheKey key) { return Remove(BuildUniqueStringKey(key)); }
private static bool RemoveFromCache(ICacheKey key) { lock (ActiveLock) { ICacheItem item; if (QueryResultCache.TryRemove(key, out item)) { QueryOrder.Dequeue(); CacheSize -= item.Size; return true; } else { return false; } } }
protected override void OnHit(ICacheKey key, ref object value) { base.OnHit(key, ref value); HitCount++; }
protected virtual void OnHit(ICacheKey key, ref object value) { if (Hit != null) { var args = new CacheEventArgs(key, value); Hit(this, args); value = args.Value; } }
protected virtual void OnMiss(ICacheKey key, out object value) { if (Miss != null) { var args = new CacheEventArgs(key); Miss(this, args); value = args.Value; } else { value = null; } }
public bool Contains(ICacheKey key) { if (this.Enabled) { return (this.cache[(CacheKey)key] != null); } return false; }
/// <summary> /// 初始化基缓存管理器 /// </summary> /// <param name="provider">缓存提供程序</param> /// <param name="cacheKey">缓存键</param> public DefaultCacheManager(ICacheProvider provider, ICacheKey cacheKey) : base(provider, cacheKey) { }
protected void Remove(ICacheKey key) { Remove(BuildUniqueStringKey(key)); }
public bool TryGetValue(ICacheKey cacheKey, out object value) { return _dic.TryGetValue(cacheKey, out value); }
public void SetKeyValue(ICacheKey cacheKey, object cacheValue) { _dic[cacheKey] = cacheValue; }
public void AddKeyValue(ICacheKey cacheKey, object cacheValue) { _dic.Add(cacheKey, cacheValue); }
protected abstract void OnMiss(ICacheKey key, out object value);
private bool ShouldCache(ICacheKey key) { if (this.caches.ContainsKey(key.CacheName)) { return this.Enabled && this.caches[key.CacheName] != CacheDuration.NotCached; } return false; }
public CacheEventArgs(ICacheKey key) { Key = key; }
public void Add(ICacheKey key, object value, CacheDuration cacheDuration) { if (this.ShouldCache(key)) { this.cache.Add( (CacheKey)key, value, null, DateTime.Now.AddSeconds(this.DurationInSeconds(cacheDuration)), TimeSpan.Zero, CacheItemPriority.Normal, null); } }
protected void Add(ICacheKey key, object value) { if (_useSlidingExpiration) { Add(BuildUniqueStringKey(key), value, SlidingExpirationSpan); } else if (_useAbsoluteExpiration) { Add(BuildUniqueStringKey(key), value, AbsoluteExpiration); } }
public CacheEventArgs(ICacheKey key, object value) { Key = key; Value = value; }
protected object Get(ICacheKey key) { string itemKey = BuildUniqueStringKey(key); if (Logger.IsInfoEnabled) { Logger.Info("Getting item with key: {0}", key); } object value = Get(itemKey); if (value == null) { if (Logger.IsInfoEnabled) { Logger.Info("Item with key: {0} not found in cache.", key); } //Lock only single (new) item instead of whole cache lock (GetSyncObject(itemKey)) { if (Logger.IsInfoEnabled) { Logger.Info("Trying to get item with key: {0} once more - from memory barrier.", key); } value = Get(itemKey); if (value == null) { if (Logger.IsInfoEnabled) { Logger.Info("Item with key: {0} not found in cache.", key); } OnMiss(key, out value); } else { if (Logger.IsInfoEnabled) { Logger.Info("Item with key: {0} found in cache.", key); } OnHit(key, ref value); } RemoveSyncObject(itemKey); } } else { if (Logger.IsInfoEnabled) { Logger.Info("Item with key: {0} found in cache.", key); } OnHit(key, ref value); } return value; }
public void Remove(ICacheKey key) { if (this.Enabled) { this.cache.Remove((CacheKey)key); } }