/// <summary> /// Gets the object from the cache /// </summary> /// <param name="key">Key of object to get</param> /// <returns>Cached object</returns> public object Get(object key) { if (key == null) { return(null); } try { var value = Cache.Get(key.ToString(), _appFabricRegionName); return(value == null ? null : AppFabricCacheOptimizer.Decompress((byte[])value)); } catch (DataCacheException ex) { if (IsRegionAbsent(ex)) { //Skip this exception since we don't create regions for all entities by default, but only when it's required. } else if (IsNotCritical(ex)) { _log.Warn(ex.Message, ex); } else { _log.Error(ex.Message, ex); } return(null); } }
/// <summary> /// Caches an item. /// If the region in which the item should be cached doesn't exist, it will be created. /// </summary> /// <param name="key">The key for the item to be cached.</param> /// <param name="value">The item to be cached.</param> /// <param name="createMissingRegion">A flag to determine whether or not the cache region should be created if it /// doesn't exist.</param> private void Put(object key, object value, bool createMissingRegion) { if (key == null) { throw new ArgumentNullException("key"); } if (value == null) { throw new ArgumentNullException("value"); } try { var optimizedValue = AppFabricCacheOptimizer.Compress(value); //Entity cache is locked if (_lockHandles.ContainsKey(key.ToString())) { if (_expirationTimeout.HasValue) { Cache.PutAndUnlock(key.ToString(), optimizedValue, _lockHandles[key.ToString()], TimeSpan.FromMilliseconds(_expirationTimeout.Value), _appFabricRegionName); } else { Cache.PutAndUnlock(key.ToString(), optimizedValue, _lockHandles[key.ToString()], _appFabricRegionName); } lock (_lockHandles) { _lockHandles.Remove(key.ToString()); } } //Entity cache isn't locked else { if (_expirationTimeout.HasValue) { Cache.Put(key.ToString(), optimizedValue, TimeSpan.FromMilliseconds(_expirationTimeout.Value), _appFabricRegionName); } else { Cache.Put(key.ToString(), optimizedValue, _appFabricRegionName); } } } catch (DataCacheException ex) { if (IsRegionAbsent(ex) && createMissingRegion) { CreateRegionAndTryAgain(x => Put(key, value, false)); } else if (IsNotCritical(ex) || ex.ErrorCode == DataCacheErrorCode.ObjectLocked) { _log.Warn(ex.Message, ex); } else { _log.Error(ex.Message, ex); } } }