Пример #1
0
        public void TestTwoLevelCache()
        {
            var    hundredBytes = new byte[100];
            ICache primary      = new MemoryCache(500, new LruCacheEvictionPolicy(), 400, 300);
            ICache secondary    = new MemoryCache(1000, new LruCacheEvictionPolicy(), 900, 700);
            ICache cache        = new TwoLevelCache(primary, secondary);

            for (int i = 0; i < 9; i++)
            {
                cache.Insert("Entry " + i, hundredBytes, CachePriority.Normal);
                Thread.Sleep(20);
            }

            for (int i = 0; i < 9; i++)
            {
                Assert.IsTrue(secondary.ContainsKey("Entry " + i), "Expected secondary cache to contain Entry {0} after initialization");
                if (i < 5)
                {
                    Assert.IsFalse(primary.ContainsKey("Entry " + i), "Expected primary cache to NOT contain Entry {0} after initialization", i);
                }
                else
                {
                    Assert.IsTrue(primary.ContainsKey("Entry " + i), "Expected primary cache to contain Entry {0} after initialization", i);
                }
            }

            cache.Insert("Entry 10", hundredBytes, CachePriority.Normal);
            Assert.IsFalse(cache.ContainsKey("Entry 0"));
            Assert.IsFalse(cache.ContainsKey("Entry 1"));
            Assert.IsTrue(cache.ContainsKey("Entry 2"));
            Assert.IsTrue(cache.ContainsKey("Entry 10"));
            Assert.IsTrue(primary.ContainsKey("Entry 10"));
            Assert.IsTrue(secondary.ContainsKey("Entry 10"));
        }
Пример #2
0
        public void TestCacheCleanupBiggerThanCacheSize()
        {
            MemoryCache <string, int> cache = new MemoryCache <string, int>(1, 3);

            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);
#if !NETCORE
            Assert.IsTrue(cache.ContainsKey("test3"));
            Assert.AreEqual(1, cache.Count);
#else
            Assert.True(cache.ContainsKey("test3"));
            Assert.Equal(1, cache.Count);
#endif
        }
Пример #3
0
        public void TestCacheCleanupOnlyAdd()
        {
            MemoryCache <string, int> cache = new MemoryCache <string, int>(3, 1);

            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);
            cache.GetOrAdd("test4", k => 3);
#if !NETCORE
            Assert.IsFalse(cache.ContainsKey("test1"));
            Assert.AreEqual(3, cache.Count);
#else
            Assert.False(cache.ContainsKey("test1"));
            Assert.Equal(3, cache.Count);
#endif
        }
Пример #4
0
        public void LimitTest1()
        {
            IMemoryCache cache = new MemoryCache(
                new MemoryCacheOptions()
            {
                EntriesSizeLimit = 3,
            });

            cache.CreateEntry(1).SetPriority(CacheItemPriority.NeverRemove);
            cache.CreateEntry(2).SetPriority(CacheItemPriority.Low);
            cache.CreateEntry(3).SetPriority(CacheItemPriority.Normal);
            cache.CreateEntry(4).SetPriority(CacheItemPriority.Normal);

            Assert.False(cache.ContainsKey(2));
            Assert.True(cache.ContainsKey(1));
            Assert.True(cache.ContainsKey(3));
            Assert.True(cache.ContainsKey(4));
            Assert.True(cache.TrySet(5, new CacheEntry(5)));
        }
Пример #5
0
        public void TestCacheCleanupBiggerThanCacheSize()
        {
            MemoryCache<string, int> cache = new MemoryCache<string, int>(1, 3);
            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);

            Assert.IsTrue(cache.ContainsKey("test3"));
            Assert.AreEqual(1, cache.Count);
        }
Пример #6
0
        public void TestCacheCleanupOnlyAdd()
        {
            MemoryCache<string, int> cache = new MemoryCache<string, int>(3, 1);
            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);
            cache.GetOrAdd("test4", k => 3);

            Assert.IsFalse(cache.ContainsKey("test1"));
            Assert.AreEqual(3, cache.Count);
        }
Пример #7
0
        public void TestCacheCleanupRetrieve()
        {
            MemoryCache <string, int> cache = new MemoryCache <string, int>(3, 1);

            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);

            Assert.AreEqual(1, cache["test1"]);

            cache.GetOrAdd("test4", k => 3);

            Assert.IsTrue(cache.ContainsKey("test1"));
            Assert.AreEqual(3, cache.Count);
        }
Пример #8
0
        /// <summary>
        /// MemoryCache 获取或创建
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="key"></param>
        /// <param name="action"></param>
        /// <param name="expire">缓存时间秒,小于0时使用默认缓存时间</param>
        /// <returns></returns>
        public static TResult GetCache <TResult>(string key, Func <TResult> action, int expire = -1)
        {
            TResult result = default(TResult);

            //1.0 从缓存中取KEY对应的数据,如果不存在则使用action回调获取,并缓存起来
            if (MemoryCache.ContainsKey(key))
            {
                return(MemoryCache.Get <TResult>(key));
            }
            else
            {
                result = action();
                MemoryCache.Set <TResult>(key, result, expire);
                return(result);
            }
        }
Пример #9
0
        public void GetCollectionTest1()
        {
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

            cache.CreateEntry(1);
            cache.CreateEntry(2);
            cache.CreateEntry(3);

            var collection = cache.GetCacheCollection();

            cache.Remove(1);

            Assert.NotEmpty(collection);
            Assert.Equal(3, collection.Count());
            Assert.False(cache.ContainsKey(1));
        }
Пример #10
0
        public void TestQueryCacheInsertAndInvalidation()
        {
            var testCache = new MemoryCache(8192, new LruCacheEvictionPolicy());
            var client    = GetClient(testCache);
            var storeName = "Client.TestQueryCacheInvalidation_" + DateTime.Now.Ticks;

            client.CreateStore(storeName);
            const string query = "SELECT ?s WHERE { ?s ?p ?o }";

            client.ExecuteQuery(storeName, query);
            var cacheKey = storeName + "_" + query.GetHashCode() + "_" + SparqlResultsFormat.Xml;

            Assert.IsTrue(testCache.ContainsKey(cacheKey));
            testCache.Insert(cacheKey, new CachedQueryResult(DateTime.UtcNow, "This is a test"), CachePriority.Normal);
            var    resultStream = client.ExecuteQuery(storeName, query);
            string result;

            using (var resultReader = new StreamReader(resultStream))
            {
                result = resultReader.ReadToEnd();
            }
            Assert.AreEqual("This is a test", result);

            Thread.Sleep(1000); // Allow for resolution of Last-Modified header

            client.ExecuteTransaction(storeName,
                                      new UpdateTransactionData
            {
                InsertData =
                    "<http://example.org/s> <http://example.org/p> <http://example.org/o> ."
            });

            resultStream = client.ExecuteQuery(storeName, query);
            using (var resultReader = new StreamReader(resultStream))
            {
                result = resultReader.ReadToEnd();
            }
            // We should not get the test result we inserted into the cache this time.
            Assert.AreNotEqual("This is a test", result);

            // The cache should have been updated with the result received from the server.
            var cacheResult = testCache.Lookup <CachedQueryResult>(cacheKey);

            Assert.AreEqual(result, cacheResult.Result);
        }
Пример #11
0
        public void TestValueIsNotInCache()
        {
            var hasherMock = new Mock <IHasher>();

            hasherMock.Setup(h => h.GetHash(It.IsAny <IMessage>()))
            .Returns("non-existing-hash");
            var cache = new MemoryCache(hasherMock.Object);
            var key   = new Message <string>(MessageLabel.From("label"), "payload");

            var containsCachedValue = cache.ContainsKey(key);
            var cachedValue         = containsCachedValue ? cache[key] : null;

            Assert.IsFalse(containsCachedValue, "cache should not contain value not cached before");
            Assert.IsNull(cachedValue, "value for not cached key should be null'");

            // teardown because of using MemoryCache.Default
            cache.Set(key, string.Empty, TimeSpan.Zero);
        }
Пример #12
0
        public void TestCacheIsSet()
        {
            var hasherMock = new Mock <IHasher>();

            hasherMock.Setup(h => h.GetHash(It.IsAny <IMessage>()))
            .Returns("hash");
            var cache = new MemoryCache(hasherMock.Object);
            var key   = new Message <string>(MessageLabel.From("label"), "payload");
            var value = "value";

            cache.Set(key, value, TimeSpan.FromMinutes(1.0));
            var containsCachedValue = cache.ContainsKey(key);
            var cachedValue         = containsCachedValue ? cache[key] : null;

            Assert.IsTrue(containsCachedValue, "cache should contain cached value");
            Assert.AreEqual(value, cachedValue, $"cached value should be equal to '{value}'");

            // teardown because of using MemoryCache.Default
            cache.Set(key, string.Empty, TimeSpan.Zero);
        }
Пример #13
0
        public void GetCollectionTest2()
        {
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()
            {
                ExpirationScanFrequency = TimeSpan.FromSeconds(1)
            });

            cache.CreateEntry(1).SetAbsoluteExpiration(TimeSpan.FromSeconds(1));
            var beforeCollection = cache.GetCacheCollection();

            Thread.Sleep(1500);

            // HACK: deletion of entities happens in the background so the first result can be TRUE
            if (cache.ContainsKey(1))
            {
                Thread.Sleep(500);
            }

            var afterCollection = cache.GetCacheCollection();

            Assert.NotNull(beforeCollection.FirstOrDefault(o => o.Key.Equals(1)));
            Assert.Null(afterCollection.FirstOrDefault(o => o.Key.Equals(1)));
        }
Пример #14
0
        public void TestLruPolicy()
        {
            var    hundredBytes = new byte[100];
            ICache cache        = new MemoryCache(1000, new LruCacheEvictionPolicy(), 900, 700);

            for (int i = 0; i < 9; i++)
            {
                cache.Insert("Entry " + i, hundredBytes, CachePriority.Normal);
                Thread.Sleep(20);
            }
            // Cache size is now 900 bytes

            cache.Insert("Entry 10", hundredBytes, CachePriority.Normal);
            Assert.IsFalse(cache.ContainsKey("Entry 0"));
            Assert.IsFalse(cache.ContainsKey("Entry 1"));
            Assert.IsTrue(cache.ContainsKey("Entry 2"));
            Assert.IsTrue(cache.ContainsKey("Entry 10"));

            // Cache size should now be 800 bytes
            cache.Lookup("Entry 2");
            cache.Insert("Entry 11", hundredBytes, CachePriority.Normal);
            cache.Insert("Entry 12", hundredBytes, CachePriority.Normal);                                                 // This insert should force eviction
            Assert.IsFalse(cache.ContainsKey("Entry 0"));                                                                 // was previously evicted
            Assert.IsFalse(cache.ContainsKey("Entry 1"));                                                                 // was previously evicted
            Assert.IsTrue(cache.ContainsKey("Entry 2"), "Expected Entry2 to remain in cache after second eviction");      // Won't be evicted due to recent access
            Assert.IsFalse(cache.ContainsKey("Entry 3"));                                                                 // newly evicted
            Assert.IsFalse(cache.ContainsKey("Entry 4"));                                                                 // newly evicted
            Assert.IsTrue(cache.ContainsKey("Entry 5"), "Expected Entry 5 to remain in cache after second eviction");     // shouldn't be evicted
            Assert.IsTrue(cache.ContainsKey("Entry 11"), "Expected Entry 11 to remain in cache after second eviction");   // should have been added before eviction
            Assert.IsTrue(cache.ContainsKey("Entry 12"), "Expected Entry 12 to be added to cache after second eviction"); // should have been added after eviction
        }
Пример #15
0
        public void TestLruPriority()
        {
            var    hundredBytes = new byte[100];
            ICache cache        = new MemoryCache(1000, new LruCacheEvictionPolicy(), 900, 700);

            for (int i = 0; i < 9; i++)
            {
                cache.Insert("Entry " + i, hundredBytes, i % 2 == 0 ? CachePriority.High : CachePriority.Normal);
                Thread.Sleep(20);
            }
            // Cache size is now 900 bytes

            cache.Insert("Entry 10", hundredBytes, CachePriority.High);
            Assert.IsTrue(cache.ContainsKey("Entry 0"), "Expected Entry 0 to remain after first eviction");
            Assert.IsFalse(cache.ContainsKey("Entry 1"), "Expected Entry 1 to be removed after first eviction");
            Assert.IsTrue(cache.ContainsKey("Entry 2"), "Expected Entry 2 to remain after first eviction");
            Assert.IsFalse(cache.ContainsKey("Entry 3"), "Expected Entry 3 to be removed after first eviction");
            Assert.IsTrue(cache.ContainsKey("Entry 4"));
            Assert.IsTrue(cache.ContainsKey("Entry 5"));
            Assert.IsTrue(cache.ContainsKey("Entry 10"));

            cache.Insert("Entry 11", hundredBytes, CachePriority.High);
            cache.Insert("Entry 12", hundredBytes, CachePriority.High);
            Assert.IsFalse(cache.ContainsKey("Entry 5"), "Expected Entry 5 to be removed after second eviction");
            Assert.IsFalse(cache.ContainsKey("Entry 7"), "Expected Entry 7 to be removed after second eviction");

            Assert.IsNotNull(cache.Lookup("Entry 2"));
            cache.Insert("Entry 13", hundredBytes, CachePriority.High);
            cache.Insert("Entry 14", hundredBytes, CachePriority.High);
            Assert.IsFalse(cache.ContainsKey("Entry 0")); // Should now start evicting high priority items
            Assert.IsTrue(cache.ContainsKey("Entry 2"), "Expected Entry 2 to remain after third eviction due to recent access");
            Assert.IsFalse(cache.ContainsKey("Entry 4"), "Expected Entry 4 to be removed after third eviction");
        }
Пример #16
0
 private bool IsInFormulaCache(string formulaText)
 {
     return(cacheEnabled && executionFormulaCache.ContainsKey(formulaText));
 }