Esempio n. 1
0
        public void AddOrUpdate_SuccessfullyUpdatesCache_ByReturningUpdatedValue()
        {
            //Arrange
            CacheTestData data = new CacheTestData()
            {
                ExpectedValue = "2"
            };

            //Act
            try
            {
                AddMembers(2);
                //Test updating the value of the first key to 2, instead of the default 0.
                _cache.AddOrUpdate(0, "2");
                _cache.TryGetValue(0, out data.Value);
            }
            catch (Exception e)
            {
                data.Errors = e.Message;
            }

            //Assert
            Assert.That(data.Errors, Is.Null.Or.Empty, $"Expected there to be no exceptions during update. Error: {data.Errors}.");
            Assert.That(data.Value, Is.EqualTo(data.ExpectedValue), $"Expected value to be the updated value of {data.ExpectedValue}, not {data.Value}.");
        }
Esempio n. 2
0
        /// <summary>
        /// Adds (or replaces) an object to the specified cache context.
        /// </summary>
        /// <param name="context">The context to add the object to.</param>
        /// <param name="key">The key used to retrieve the object.</param>
        /// <param name="value">The object to be stored.</param>
        /// <returns>false if the object was updated, true if the key was added.</returns>
        /// <exception cref="System.Collections.Generic.KeyNotFoundException">Thrown when the specified context does not exist.</exception>
        public static bool AddOrUpdate(string context, object key, object value)
        {
            readWriteLock.AcquireReaderLock(MAX_LOCK_WAIT);
            try {
                if (caches.ContainsKey(context))
                {
                    ICache tmpCache = caches[context];

                    if (DefaultExpiryTime == 0)
                    {
                        return(tmpCache.AddOrUpdate(key, value));
                    }
                    else
                    {
                        if (tmpCache.Contains(key))
                        {
                            tmpCache.Remove(key);
                        }
                        return(tmpCache.AddOrUpdate(key, value, TimeSpan.FromSeconds(DefaultExpiryTime)));
                    }
                }
                else
                {
                    throw new KeyNotFoundException("The context '" + context + "' does not exist.");
                }
            }
            finally { readWriteLock.ReleaseReaderLock(); }
        }
Esempio n. 3
0
        public void TestGettingValues()
        {
            // Try to get value that is not in the cache
            found = cache.TryGetValue("invalid key", out val);
            Assert.Null(val);
            Assert.False(found);

            // Add 4 values to the cache
            cache.AddOrUpdate("one", 1);
            cache.AddOrUpdate("two", 2);
            cache.AddOrUpdate("three", 3);
            cache.AddOrUpdate("four", 4);

            // Try to get first element from the cache, make sure it exists there
            found = cache.TryGetValue("one", out val);
            Assert.True(val == 1);
            Assert.True(found);

            // Try to get second element, it also should be there
            found = cache.TryGetValue("two", out val);
            Assert.True(val == 2);
            Assert.True(found);

            // Try to get element that doesn't exist, make sure it's not there
            found = cache.TryGetValue("five", out val);
            Assert.Null(val);
            Assert.False(found);
        }
Esempio n. 4
0
        public static void TryGet_AddOrUpdateTwoValue_ReturnsLastValue(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue");
            cache.AddOrUpdate(1, "TestValue1234");

            var keyExists = cache.TryGet(1, out var value);

            Assert.True(keyExists);
            Assert.Equal("TestValue1234", value);
        }
Esempio n. 5
0
        public void AddOrUpdate(TObject item)
        {
            TKey key      = _keySelector.GetKey(item);
            var  previous = _cache.Lookup(key);

            _queue.Add(previous.HasValue
                               ? new Change <TObject, TKey>(ChangeReason.Update, key, item, previous)
                               : new Change <TObject, TKey>(ChangeReason.Add, key, item));
            _cache.AddOrUpdate(item, key);
        }
Esempio n. 6
0
        public void AddOrUpdate(IEnumerable <TObject> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            if (_keySelector == null)
            {
                throw new KeySelectorException("A key selector must be specified");
            }

            if (items is IList <TObject> list)
            {
                //zero allocation enumerator
                var enumerable = EnumerableIList.Create(list);
                foreach (var item in enumerable)
                {
                    _cache.AddOrUpdate(item, _keySelector(item));
                }
            }
            else
            {
                foreach (var item in items)
                {
                    _cache.AddOrUpdate(item, _keySelector(item));
                }
            }
        }
Esempio n. 7
0
        public static void GetValue_GetExistingWithRegion_ReturnsValue(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue", "region1");
            cache.AddOrUpdate(1, "TestValue2", "region2");

            var value  = cache.GetValue(1, "region1");
            var value2 = cache.GetValue(1, "region2");

            Assert.Equal("TestValue", value);
            Assert.Equal("TestValue2", value2);
        }
Esempio n. 8
0
        public static void Remove_TryGetValue_ReturnFalse(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue1");
            cache.AddOrUpdate(2, "TestValue2");
            cache.Remove(1);

            var keyExists1 = cache.TryGet(1, out _);
            var keyExists2 = cache.TryGet(2, out _);

            Assert.False(keyExists1);
            Assert.True(keyExists2);
        }
Esempio n. 9
0
        public static void Clear_TryGetValueWithRegions_ReturnFalse(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue1", "region1");
            cache.AddOrUpdate(2, "TestValue2", "region2");
            cache.Clear("region1");

            var keyExists1 = cache.TryGet(1, out _, "region1");
            var keyExists2 = cache.TryGet(2, out _, "region2");

            Assert.False(keyExists1);
            Assert.True(keyExists2);
            Assert.Equal("TestValue2", cache.GetValue(2, "region2"));
        }
Esempio n. 10
0
        public static void TryGet_KeyExistsWithRegion_ReturnsTrueAndValue(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue", "region1");
            cache.AddOrUpdate(1, "TestValue2", "region2");

            var keyExists = cache.TryGet(1, out var value, "region1");

            Assert.True(keyExists);
            Assert.Equal("TestValue", value);

            var keyExists2 = cache.TryGet(1, out var value2, "region2");

            Assert.True(keyExists2);
            Assert.Equal("TestValue2", value2);
        }
Esempio n. 11
0
        public async Task <IEnumerable <TServiceModel> > GetAll()
        {
            var items = cache.Get <IEnumerable <TServiceModel> >("all");

            if (items != null)
            {
                return(items);
            }

            items = await safeService.GetAll();

            cache.AddOrUpdate("all", items);

            return(items);
        }
Esempio n. 12
0
        public static void TryGet_KeyNotExistsWithRegion_ReturnFalse(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "Test", "region1");

            Assert.False(cache.TryGet(1, out _));
            Assert.False(cache.TryGet(1, out _, "region2"));
        }
Esempio n. 13
0
        public static T RetreiveFromCache <T>(this ICache cache, object cacheLock, string cacheKey, DateTime cacheExpiry, Func <T> notInCacheMethod) where T : class
        {
            //See if the data is already cached
            var data = cache.Get <T>(cacheKey);

            if (data != null)
            {
                return(data);
            }

            lock (cacheLock)
            {
                //double check in case cache was locked by idetical call
                data = cache.Get <T>(cacheKey);

                if (data != null)
                {
                    return(data);
                }

                data = notInCacheMethod();

                cache.AddOrUpdate(cacheKey, data, cacheExpiry);
                return(data);
            }
        }
Esempio n. 14
0
        ////////////////////////////////////////////////////////////
        // IImprovedAssetCache
        //

        public void Cache(string assetID, AssetBase asset)
        {
            if (asset != null)
            {
                m_Cache.AddOrUpdate(asset.IDString, asset);
            }
        }
        internal static T GetOrAddImpl <T>(ICache cache, string key, Func <string, T> constructor,
                                           object cachePolicy = null)
        {
            lock (cache.LockKey)
            {
                CacheItem <T> existingItem = cache.GetCacheItem <T>(key);
                if (existingItem != null)
                {
                    return(existingItem.Value);
                }
            }

            // Note: it's possible that another thread will have already added an item into the cache with our key
            // if this has happened we're going to discard what constructor returns and return what's in the cache
            // - this mirrors the behaviour of ConcurrentDictionary
            // IMPORTANT: what we do NOT want to do is extend the lock above to include the call to constructor as we
            // have no way of knowing how long we would have to wait blocking access to the cache
            // If this is a problem for your use case, then use IMultiThreadProtectedCache which will guarantee that
            // constructor function will only run once
            T newValue = constructor(key);

            lock (cache.LockKey)
            {
                CacheItem <T> existingItem = cache.GetCacheItem <T>(key);
                if (existingItem != null)
                {
                    return(existingItem.Value);
                }
                cache.AddOrUpdate(key, newValue, cachePolicy);
                return(newValue);
            }
        }
        ////////////////////////////////////////////////////////////
        // IImprovedAssetCache
        //

        public void Cache(AssetBase asset)
        {
            if (asset != null)
            {
                m_Cache.AddOrUpdate(asset.ID, asset);
            }
        }
Esempio n. 17
0
        private async Task <bool> UpdateCacheAndAttemptRetrieval(ICache <int, string> cache, int key, int pauseInMilliseconds)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(pauseInMilliseconds));

            var expectedValue = key.ToString();

            Console.WriteLine($"Updating {key}...");
            cache.AddOrUpdate(key, expectedValue);

            await Task.Delay(TimeSpan.FromSeconds(2));

            Console.WriteLine($"Retrieving key {key}...");
            var result = cache.TryGetValue(key, out var actualValue);

            if (result)
            {
                Console.WriteLine($"Cache hit on {key}.");
                Assert.That(actualValue, Is.EqualTo(expectedValue));
            }
            else
            {
                Console.WriteLine($"Cache missed on {key}.");
            }
            return(result);
        }
Esempio n. 18
0
        public static void GetValue_GetExisting_ReturnsValue(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue");

            var value = cache.GetValue(1);

            Assert.Equal("TestValue", value);
        }
Esempio n. 19
0
        public static async Task TryGetAsync_KeyNotExistsWithRegion_ReturnFalse(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "Test", "region1");

            var cacheRequestResult = await cache.TryGetAsync(1).ConfigureAwait(false);

            Assert.False(cacheRequestResult.EntryExists);
        }
Esempio n. 20
0
        public static async Task GetValueAsync_KeyNotExistsWithRegions_ReturnNull(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue", "region1");

            var value = await cache.GetValueAsync(1, false).ConfigureAwait(false);

            Assert.Null(value);
        }
Esempio n. 21
0
        public static void GetValue_KeyNotExistsWithRegions_ReturnNull(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue", "region1");

            var value = cache.GetValue(1, false);

            Assert.Null(value);
        }
Esempio n. 22
0
        public static void Remove_WithRegionsTryGetValue_ReturnFalse(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue1", "region1");
            cache.AddOrUpdate(1, "TestValue1", "region2");
            cache.AddOrUpdate(2, "TestValue2", "region1");
            cache.AddOrUpdate(2, "TestValue2", "region2");
            cache.Remove(1, "region1");

            var keyExists1 = cache.TryGet(1, out _, "region1");
            var keyExists2 = cache.TryGet(1, out _, "region2");
            var keyExists3 = cache.TryGet(2, out _, "region1");
            var keyExists4 = cache.TryGet(2, out _, "region2");

            Assert.False(keyExists1);
            Assert.True(keyExists2);
            Assert.True(keyExists3);
            Assert.True(keyExists4);
        }
Esempio n. 23
0
        public static void TryGet_KeyExists_ReturnsTrueAndValue(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue");

            var keyExists = cache.TryGet(1, out var value);

            Assert.True(keyExists);
            Assert.Equal("TestValue", value);
        }
Esempio n. 24
0
        public IReadOnlyList <ChannelInfo> GetChannels()
        {
            var value = _cache.Get <IReadOnlyList <ChannelInfo> >(ResourceCacheType.Channels);

            if (value == null)
            {
                Logger.Debug("Caching...");
                value = _loader.LoadChannels().ToList();
                _cache.AddOrUpdate(ResourceCacheType.Channels, value);
            }
            return(value);
        }
Esempio n. 25
0
        public async Task <IActionResult> GetTokenWithSmallApp(string code)
        {
            var keyInfo = await _smallAppClient.GetKeyInfo(code);

            if (keyInfo.open_id == null)
            {
                return(BadRequest("获取token失败"));
            }
            var token = _customTokenProvider.GetToken();

            _cache.AddOrUpdate("token", token.access_token);
            return(Ok(token));
        }
Esempio n. 26
0
        public static async Task TryGet_AfterExpirationTimeSpan_ReturnsFalse(ICache <int, string> cache)
        {
            var expirationPolicy = A.Fake <ICacheExpirationPolicy>();

            A.CallTo(() => expirationPolicy.ExpirationMode).Returns(CacheExpirationMode.SlidingTimeSpan);

            A.CallTo(() => expirationPolicy.SlidingTimeSpan).Returns(TimeSpan.FromMilliseconds(50));

            cache.AddOrUpdate(1, "TestValue", expirationPolicy);

            await Task.Delay(100).ConfigureAwait(false);

            Assert.False(cache.TryGet(1, out _));
        }
Esempio n. 27
0
        public static void GetValue_KeyNotExistsWithRegions_ThrowsException(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue", "region1");

            var exception = Assert.Throws <CacheEntryNotFoundException>(() => cache.GetValue(1));

            Assert.Equal("1", exception.Key);
            Assert.Equal(string.Empty, exception.RegionName);

            var exception2 = Assert.Throws <CacheEntryNotFoundException>(() => cache.GetValue(1, "region2"));

            Assert.Equal("1", exception2.Key);
            Assert.Equal("region2", exception2.RegionName);
        }
Esempio n. 28
0
        /// <summary>
        /// Cache test
        /// </summary>
        /// <param name="cache">cache instance</param>
        private static void Test(ICache <string, TestData> cache)
        {
            Console.WriteLine("Cache type: {0}.{1}", cache.GetType().Namespace, cache.GetType().Name);
            Console.WriteLine("Threads: {0}, Items per thread: {1}, Reads per thread: {2}", threadCount, itemsPerThread, itemsPerThread * readOperationPerWrite);
            Stopwatch         stopwatch       = new Stopwatch();
            ManualResetEvent  mre             = new ManualResetEvent(false);
            List <WaitHandle> threadHandles   = new List <WaitHandle>();
            List <long>       memoryUsageList = new List <long>();

            for (int i = 0; i < threadCount; i++)
            {
                EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
                Thread          thread = new Thread(new ThreadStart(() =>
                {
                    mre.WaitOne();
                    Random random = new Random(DateTime.Now.Millisecond);
                    for (int j = 0; j < itemsPerThread; j++)
                    {
                        string key    = CreateKey(keyLength);
                        TestData data = CreateTestData(random);
                        cache.AddOrUpdate(key, data);
                        for (int k = 0; k < readOperationPerWrite; k++)
                        {
                            string keyToSearch = CreateKey(keyLength);
                            cache.TryGetValue(keyToSearch, out TestData cachedData);
                        }
                    }

                    handle.Set();
                }));
                thread.Start();
                threadHandles.Add(handle);
            }
            Timer memoryMonitor = new Timer(new TimerCallback(s => memoryUsageList.Add(Process.GetCurrentProcess().WorkingSet64)), null, 100, 100);

            stopwatch.Start();
            mre.Set();

            WaitHandle.WaitAll(threadHandles.ToArray());
            stopwatch.Stop();
            memoryMonitor.Dispose();

            Console.WriteLine("Time Elapsed: {0}", stopwatch.Elapsed);
            Console.WriteLine("Total reads: {0}, total writes: {1}", itemsPerThread * readOperationPerWrite * threadCount, itemsPerThread * threadCount);
            Console.WriteLine("Reads per second: {0}, writes per second: {1}", (long)((itemsPerThread * readOperationPerWrite * threadCount) / stopwatch.Elapsed.TotalSeconds), (long)((itemsPerThread * threadCount) / stopwatch.Elapsed.TotalSeconds));
            Console.WriteLine("Max memory used (MB): {0}", (long)(memoryUsageList.Max() / 1048576));
            Console.WriteLine("Average memory used (MB): {0}", (long)(memoryUsageList.Average() / 1048576));
            GC.Collect();
        }
Esempio n. 29
0
        public static async Task TryGet_AfterExpiration_ReturnsFalse(ICache <int, string> cache)
        {
            var expirationPolicy = A.Fake <ICacheExpirationPolicy>();

            A.CallTo(() => expirationPolicy.ExpirationMode).Returns(CacheExpirationMode.AbsoluteDateTime);
            var expirationDateTime = DateTime.Now;

            A.CallTo(() => expirationPolicy.AbsoluteDateTime).Returns(expirationDateTime);

            cache.AddOrUpdate(1, "TestValue", expirationPolicy);

            await Task.Delay(100).ConfigureAwait(false);

            Assert.False(cache.TryGet(1, out _));
        }
Esempio n. 30
0
        public static async Task GetValueAsync_KeyNotExistsWithRegions_ThrowsException(ICache <int, string> cache)
        {
            cache.AddOrUpdate(1, "TestValue", "region1");

            var exception =
                await Assert.ThrowsAsync <CacheEntryNotFoundException>(async() => await cache.GetValueAsync(1).ConfigureAwait(false));

            Assert.Equal("1", exception.Key);
            Assert.Equal(string.Empty, exception.RegionName);

            var exception2 =
                await Assert.ThrowsAsync <CacheEntryNotFoundException>(async() => await cache.GetValueAsync(1, "region2").ConfigureAwait(false));

            Assert.Equal("1", exception2.Key);
            Assert.Equal("region2", exception2.RegionName);
        }