Beispiel #1
0
        public bool IsCacheOverriddenForCurrentMember(string cacheKeyPrefix)
        {
            var currentMember = _membershipHelper.GetCurrentMember();

            if (currentMember == null)
            {
                return(false);
            }

            return(_cacheProvider.TryGet(CacheConstants.MemberOverridePolicy + cacheKeyPrefix + currentMember.Key).Item1);
        }
Beispiel #2
0
        public void Get_should_return_instance_previously_stored_in_cache()
        {
            Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>();
            string key         = "anything";
            var    cachedValue = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());

            mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(cachedValue).Verifiable();

            ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>();

            (bool got, byte[] fromCache) = provider.TryGet(key);

            got.Should().BeTrue();
            mockDistributedCache.Verify(v => v.Get(key), Times.Once);
            fromCache.Should().BeSameAs(cachedValue);
        }
Beispiel #3
0
        public void Get_should_return_instance_previously_stored_in_cache()
        {
            Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>();
            string key          = "anything";
            string valueToCache = Guid.NewGuid().ToString();

            mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(Encoding.UTF8.GetBytes(valueToCache)).Verifiable(); // Because GetString() is an extension method, we cannot mock it.  We mock Get() instead.

            ISyncCacheProvider <string> provider = mockDistributedCache.Object.AsSyncCacheProvider <string>();

            (bool got, string fromCache) = provider.TryGet(key);

            got.Should().BeTrue();
            mockDistributedCache.Verify(v => v.Get(key), Times.Once);
            fromCache.Should().Be(valueToCache);
        }
Beispiel #4
0
        public void Get_should_return_false_on_unknown_key()
        {
            Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>();
            string key         = "anything";
            var    cachedValue = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());

            mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(cachedValue).Verifiable();
            mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k != key))).Returns((byte[])null).Verifiable();

            ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>();
            string someOtherKey = Guid.NewGuid().ToString();

            (bool got, byte[] fromCache) = provider.TryGet(someOtherKey);

            got.Should().BeFalse();
            mockDistributedCache.Verify(v => v.Get(someOtherKey), Times.Once);
            fromCache.Should().BeNull();
        }
Beispiel #5
0
        /// <inheritdoc />>
        public async Task <T> GetCachedDataAsync(Func <CancellationToken, Task <T> > dataGetter, string key, RefreshBehaviour refreshBehaviour, CancellationToken cancellationToken, NotInCacheBehaviour notInCacheBehaviour)
        {
            (bool, object)memoryWrappedResult = _pollySyncCacheProvider.TryGet(key);

            bool isObjectInMemoryCache = memoryWrappedResult.Item1;

            if (isObjectInMemoryCache)
            {
                CachedItemWrapper <T> memoryResultObject = (CachedItemWrapper <T>)memoryWrappedResult.Item2;
                bool isMemoryCacheFresh = IsFresh(memoryResultObject);

                if (!isMemoryCacheFresh)
                {
                    if (refreshBehaviour == RefreshBehaviour.WaitForFreshData)
                    {
                        return(await _collapserPolicy.ExecuteAsync(async() => await RecacheItemInMemoryCacheAsync(dataGetter, key, cancellationToken, _whenDataIsStaleDelegate)));
                    }
                    else if (refreshBehaviour == RefreshBehaviour.DontWaitForFreshData)
                    {
#pragma warning disable 4014
                        Task.Factory.StartNew(async() => await RecacheItemInMemoryCacheAsync(dataGetter, key, cancellationToken, _whenDataIsStaleDelegate), cancellationToken);
#pragma warning restore 4014
                    }
                }

                return(memoryResultObject.Content);
            }

            if (notInCacheBehaviour == NotInCacheBehaviour.WaitForData)
            {
                return(await RecacheItemInMemoryCacheAsync(dataGetter, key, cancellationToken, _whenDataIsStaleDelegate));
            }
            else if (notInCacheBehaviour == NotInCacheBehaviour.DontWaitForData)
            {
#pragma warning disable 4014
                Task.Factory.StartNew(async() => await RecacheItemInMemoryCacheAsync(dataGetter, key, cancellationToken, _whenDataIsStaleDelegate), cancellationToken);
#pragma warning restore 4014
            }

            return(default);
Beispiel #6
0
        internal static TResult Implementation <TResult>(
            ISyncCacheProvider <TResult> cacheProvider,
            ITtlStrategy <TResult> ttlStrategy,
            Func <Context, string> cacheKeyStrategy,
            Func <Context, CancellationToken, TResult> action,
            Context context,
            CancellationToken cancellationToken,
            Action <Context, string> onCacheGet,
            Action <Context, string> onCacheMiss,
            Action <Context, string> onCachePut,
            Action <Context, string, Exception> onCacheGetError,
            Action <Context, string, Exception> onCachePutError)
        {
            cancellationToken.ThrowIfCancellationRequested();

            string cacheKey = cacheKeyStrategy(context);

            if (cacheKey == null)
            {
                return(action(context, cancellationToken));
            }

            bool    cacheHit;
            TResult valueFromCache;

            try
            {
                (cacheHit, valueFromCache) = cacheProvider.TryGet(cacheKey);
            }
            catch (Exception ex)
            {
                cacheHit       = false;
                valueFromCache = default;
                onCacheGetError(context, cacheKey, ex);
            }
            if (cacheHit)
            {
                onCacheGet(context, cacheKey);
                return(valueFromCache);
            }
            else
            {
                onCacheMiss(context, cacheKey);
            }

            TResult result = action(context, cancellationToken);

            Ttl ttl = ttlStrategy.GetTtl(context, result);

            if (ttl.Timespan > TimeSpan.Zero)
            {
                try
                {
                    cacheProvider.Put(cacheKey, result, ttl);
                    onCachePut(context, cacheKey);
                }
                catch (Exception ex)
                {
                    onCachePutError(context, cacheKey, ex);
                }
            }

            return(result);
        }
 /// <summary>
 /// Gets a value from the cache.
 /// </summary>
 /// <param name="key">The cache key.</param>
 /// <returns>
 /// A tuple whose first element is a value indicating whether the key was found in the cache,
 /// and whose second element is the value from the cache (null if not found).
 /// </returns>
 public (bool, object) TryGet(string key)
 {
     (bool cacheHit, TSerialized objectToDeserialize) = _wrappedCacheProvider.TryGet(key);
     return(cacheHit, cacheHit ? _serializer.Deserialize(objectToDeserialize) : null);
 }