public void AddCache(string cacheKey, ISQLCacheItem cacheItem, int cacheTime, int duringTime) { if (cacheTime == -1) { m_cache.TryAdd(cacheKey, cacheItem); } else { if (cacheTime > 0) { _memoryCache.Add(new CacheItem(cacheKey) { Key = cacheKey, Value = cacheItem }, new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now, new TimeSpan(0, 0, cacheTime)) }); } else if (duringTime > 0) { _memoryCache.Add(new CacheItem(cacheKey) { Key = cacheKey, Value = cacheItem }, new CacheItemPolicy { SlidingExpiration = new TimeSpan(0, 0, duringTime) }); } } }
public void CrearCacheHorasTotales() { var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddDays(1) }; OdbcConnection con = new OdbcConnection(connectionString); string queryString = "SELECT No_Cuenta, sum(Horas_Acum) FROM [Tabla General] Group By No_Cuenta;"; OdbcCommand command = new OdbcCommand(queryString, con); con.Open(); OdbcDataReader reader = command.ExecuteReader(); //Console.WriteLine(reader.FieldCount); while (reader.Read()) { var cacheIt = new CacheItem(reader.GetString(0), reader.GetString(1)); cache.Add(cacheIt, cacheItemPolicy); } reader.Close(); var chek = cache.Get("21841180"); //Console.WriteLine(chek); /*foreach (var item in cache) * { * Console.WriteLine($"{item.Key} : {item.Value}"); * }*/ Console.WriteLine("Caché creado con éxito!"); }
public void ClearAllCachesTest() { const string prefix = "123123af"; var fk1 = FullKey(prefix, "111"); var fk2 = FullKey(prefix, "222"); var memoryCache = new MemoryCache("sdgkmnsdlkghn"); _objectCacheFactory.Setup(x => x.Create()).Returns(memoryCache).Verifiable(); Assert.AreEqual(0, memoryCache.GetCount()); memoryCache.Add(fk1, new MemoryCacherTests.One(), new CacheItemPolicy()); memoryCache.Add(fk2, new MemoryCacherTests.One(), new CacheItemPolicy()); Assert.AreEqual(2, memoryCache.Count()); new CacheCleaner(_objectCacheFactory.Object).Clean(); Assert.AreEqual(0, memoryCache.GetCount()); }
private void StoreRootCacheKey() { rootCacheKeyStored = true; cache.Add( rootCacheKey, rootCacheKey, new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable, RemovedCallback = new CacheEntryRemovedCallback(args => { rootCacheKeyStored = false; }) }); }
/// <summary> /// Get cached item. /// </summary> /// <typeparam name="T">item type</typeparam> /// <param name="key">item key</param> /// <param name="getItem">get item function</param> /// <param name="update">if true force item update via getItem, otherwise default behavior</param> /// <returns>item</returns> public T Get <T>(NonNullable <string> key, Func <T> getItem, bool update) where T : class { if (!update && _cache.Get(CacheKey <T>(key)) is T item) { return(item); } item = getItem(); var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMilliseconds(_lifetimeMilliseconds) }; _cache.Add(CacheItem(key, item), cacheItemPolicy); return(item); }
public void ShouldExpireCacheAfterConfigurableTime() { const string PolicyKey = "MDM.Market"; var appSettings = new NameValueCollection(); appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8"; var configManager = new Mock<IConfigurationManager>(); configManager.Setup(x => x.AppSettings).Returns(appSettings); ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object); var policyItem = policyFactory.CreatePolicy(); var marketName = "ABC market"; var marketKey = "Market-1"; var cache = new MemoryCache("MDM.Market"); cache.Add(marketKey, marketName, policyItem); // Should get cache item Assert.AreEqual(marketName, cache[marketKey]); // Keep on accessing cache, it should expire approximately with in 10 iterations int count = 0; while (cache[marketKey] != null && count < 10) { count++; Thread.Sleep(TimeSpan.FromSeconds(1)); } Console.WriteLine("Cache has expired in {0} seconds:", count); // should not be in the cache after configuratble time Assert.IsNull(cache[marketKey]); }
public void ShouldCreateAbsoluteCacheItemPolicyBasedOnTheConfiguration() { const string PolicyKey = "MDM.Market"; var appSettings = new NameValueCollection(); appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8"; var configManager = new Mock<IConfigurationManager>(); configManager.Setup(x => x.AppSettings).Returns(appSettings); ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object); var policyItem = policyFactory.CreatePolicy(); var marketName = "ABC market"; var marketKey = "Market-1"; var cache = new MemoryCache("MDM.Market"); cache.Add(marketKey, marketName, policyItem); // Should get cache item Assert.AreEqual(marketName, cache[marketKey]); // wait until the expiry time Thread.Sleep(TimeSpan.FromSeconds(10)); // should not be in the cache Assert.IsNull(cache[marketKey]); }
public void Add(string key, object o, TimeSpan?expiry, When when) { lock (_lockObj) { if (when == When.Exists && !_cache.Contains(key)) { return; } if (when == When.NotExists && _cache.Contains(key)) { return; } _cache.Remove(key); CacheItemPolicy policy = new CacheItemPolicy(); if (expiry.HasValue && expiry.Value != default(TimeSpan)) { //Store the ttl separately _ttls[key] = policy.AbsoluteExpiration = DateTime.UtcNow.Add(expiry.Value); } else { _ttls[key] = null; } System.Diagnostics.Debug.WriteLine("Adding key to mem cache: " + key); _cache.Add(key, o, policy); } }
/// <summary> /// 新增缓存项 /// </summary> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <param name="expireTime">过期时间</param> public void SetCache <T>(string key, T value, DateTime expireTime) { var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = expireTime; mc.Add(new CacheItem(key, value), policy); }
/// <summary> /// Sets the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <param name="ttl">The TTL.</param> /// <param name="overwrite">if set to <c>true</c> [overwrite].</param> public void Set(string id, string propertyName, object value, TimeSpan?ttl = null, bool overwrite = true) { if (!ttl.HasValue) { ttl = _defaultTtl; } if (overwrite) { _cache.Set(getPropertyId(id, propertyName), value, getCacheItemPolicy(ttl.Value)); } else { _cache.Add(getPropertyId(id, propertyName), value, getCacheItemPolicy(ttl.Value)); } }
public void Set(Guid id, AggregateRoot aggregate) { #if NET461 _cache.Add(id.ToString(), aggregate, _policyFactory.Invoke()); #else _cache.Set(id, aggregate, _cacheOptions); #endif }
public void Set(string id, AggregateRoot aggregate) { #if NET451 _cache.Add(id, aggregate, _policyFactory.Invoke()); #else _cache.Set(id, aggregate, _cacheOptions); #endif }
public void Put(object key, object value) { if (key == null) { throw new ArgumentNullException("key", "null key not allowed"); } if (value == null) { throw new ArgumentNullException("value", "null value not allowed"); } var cacheKey = GetCacheKey(key); if (cache[cacheKey] != null) { if (log.IsDebugEnabled) { log.Debug(string.Format("updating value of key '{0}' to '{1}'.", cacheKey, value)); } // Remove the key to re-add it again below cache.Remove(cacheKey); } else { if (log.IsDebugEnabled) { log.Debug(string.Format("adding new data: key={0}&value={1}", cacheKey, value)); } } if (!rootCacheKeyStored) { StoreRootCacheKey(); } var entry = new DictionaryEntry(key, value); var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.Add(expiration), SlidingExpiration = ObjectCache.NoSlidingExpiration }; cache.Add(cacheKey, entry, cacheItemPolicy); }
public T Get <T>(string key, Func <T> loader) { if (!_cache.Contains(key)) { _cache.Add(key, loader(), DateTimeOffset.UtcNow.AddSeconds(_config.CacheDurationSeconds)); } return((T)_cache.GetCacheItem(key).Value); }
public Task Set(Guid id, AggregateRoot aggregate) { #if NET452 _cache.Add(id.ToString(), aggregate, _policyFactory.Invoke()); #else _cache.Set(id, aggregate, _cacheOptions); #endif return(Task.FromResult(0)); }
public void Insert <T>(string key, T value, TimeSpan expiration) { var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + expiration }; _cache.Add(key, value, cacheItemPolicy); }
public static void StoreTokenInCache(string tokenId) { var cacheItemPolicy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddMinutes(30) }; _cache.Add(_key, tokenId, cacheItemPolicy); }
public void TestBasic() { var memoryCache = new MemoryCache("Foo"); var policy = new CacheItemPolicy(); memoryCache.AddOrGetExisting("Pop", 123, DateTimeOffset.MaxValue); memoryCache.AddOrGetExisting("Top", "Gun", DateTimeOffset.MaxValue); memoryCache.Add("Pop", 12, DateTime.MaxValue); Assert.AreEqual("Gun", memoryCache.Get("Top")); Assert.AreEqual(123, memoryCache.Get("Pop")); }
public void Save <T>(T aggregate, int?expectedVersion = null) where T : AggregateRoot { var idstring = aggregate.Id.ToString(); try { lock (_locks.GetOrAdd(idstring, _ => new object())) { if (aggregate.Id != Guid.Empty && !IsTracked(aggregate.Id)) { _cache.Add(idstring, aggregate, _policyFactory.Invoke()); } _repository.Save(aggregate, expectedVersion); } } catch (Exception) { _cache.Remove(idstring); throw; } }
public override void Add <T>(object objectToCache, string key, double cacheDuration) { if (objectToCache == null) { _cache.Remove(key); } else { _cache.Add(new CacheItem(key, objectToCache), new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddMinutes(cacheDuration) }); } }
public void TestCount() { MemoryCache memoryCount = new MemoryCache("count"); Desenvolvedor dev = new Desenvolvedor(); dev.Nome = "Ninja"; dev.Linguagem = "C#"; dev.AnosExperiencia = 15; CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(2); memoryCount.Add("devRemove", dev, policy); Assert.AreEqual(1, memoryCount.GetCount()); }
/// <summary> /// Stores an object in the cache. /// </summary> /// <param name="cacheKey">The cache key to store the object against.</param> /// <param name="data">The data to store against the key.</param> /// <param name="duration">The duration, in seconds, to cache the data for.</param> public virtual void SetCachedObject <T>(string cacheKey, T data, int duration) { // ReSharper disable once ConvertIfStatementToNullCoalescingExpression type conflict if (data == null) { _cache.Add(cacheKey, nullReference, DateTime.Now.AddSeconds(duration)); } else { var cacheItemPolicy = new CacheItemPolicy() //TODO to settings { SlidingExpiration = TimeSpan.FromSeconds(duration) }; _cache.Set(cacheKey, data, cacheItemPolicy); } }
public void RedisNotificationBus_WhenInvalidation_ShouldDisposeMonitor() { var lcache = new MemoryCache(Guid.NewGuid().ToString()); var bus = new RedisNotificationBus("localhost:6379", new InvalidationSettings() { TargetCache = lcache, InvalidationStrategy = InvalidationStrategyType.ChangeMonitor }); bus.Connection = this.MockOfConnection.Object; var monitor = new RedisChangeMonitor(bus.Notifier, "mykey"); lcache.Add("mykey", DateTime.UtcNow, new CacheItemPolicy() { AbsoluteExpiration = DateTime.UtcNow.AddDays(1), ChangeMonitors = { monitor } }); bus.Start(); //act this.NotificationEmitter(Constants.DEFAULT_INVALIDATION_CHANNEL, "mykey"); //assert Assert.False(lcache.Contains("mykey")); Assert.True(monitor.IsDisposed); }
public static void Set(string key, object o, int timeout) { System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default; cache.Add(TransformKey(key), o, DateTime.Now.AddMinutes(timeout)); }
/// <summary> /// Doing MemoryCaching /// </summary> /// <param name="key">Cache key</param> /// <param name="value">Cache value</param> /// <param name="cacheTime">Cache time (in minute)</param> public static void AddToCache(string key, object value, int cacheTime) { cache.Add(key, value, DateTime.Now.AddMinutes(cacheTime)); }
public void when_reading_entity_then_rehydrates() { var newEvents = new IVersionedEvent[] { new TestEvent { SourceId = id, Version = 2, Foo = "Baz" } }; var serialized = newEvents.Select(x => new EventData { Version = x.Version, Payload = Serialize(x) }); this.id = Guid.NewGuid(); var eventStore = new Mock<IEventStore>(); this.memento = Mock.Of<IMemento>(x => x.Version == 1); var cache = new MemoryCache(Guid.NewGuid().ToString()); cache.Add("TestOriginatorEntity_" + id.ToString(), new Tuple<IMemento, DateTime?>(this.memento, null), DateTimeOffset.UtcNow.AddMinutes(10)); eventStore.Setup(x => x.Load(It.IsAny<string>(), 2)).Returns(serialized); var sut = new AzureEventSourcedRepository<TestOriginatorEntity>(eventStore.Object, Mock.Of<IEventStoreBusPublisher>(), new JsonTextSerializer(), new StandardMetadataProvider(), cache); var entity = sut.Find(id); Assert.NotNull(entity); Assert.Equal(id, entity.Id); Assert.Equal(memento, entity.Memento); Assert.Equal(newEvents, entity.History, new TestEventComparer()); }
private static CacheItem CreateCacheItemAndAdd(MemoryCache target, string cacheKey, RedisChangeMonitor monitor = null) { var cacheItem = new CacheItem(cacheKey, DateTime.Now); var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.UtcNow.AddDays(1) }; if (monitor != null) policy.ChangeMonitors.Add(monitor); target.Add(cacheItem, policy); return cacheItem; }
public void TestCacheExpiryOrdering () { var config = new NameValueCollection (); config["cacheMemoryLimitMegabytes"] = 0.ToString (); config["physicalMemoryLimitPercentage"] = 100.ToString (); config["__MonoEmulateOneCPU"] = true.ToString (); // it appears that pollingInterval does nothing, so we set the Mono timer as well config["pollingInterval"] = new TimeSpan (0, 0, 1).ToString (); config["__MonoTimerPeriod"] = 1.ToString (); using (var mc = new MemoryCache ("TestCacheExpiryOrdering", config)) { Assert.AreEqual (0, mc.GetCount (), "#CEO1"); // add long lived items into the cache first for (int i = 0; i < 100; i++) { var cip = new CacheItemPolicy (); cip.SlidingExpiration = new TimeSpan (0, 0, 10); mc.Add ("long-" + i, i, cip); } Assert.AreEqual (100, mc.GetCount (), "#CEO2"); // add shorter lived items into the cache, these should expire first for (int i = 0; i < 100; i++) { var cip = new CacheItemPolicy (); cip.SlidingExpiration = new TimeSpan(0, 0, 1); mc.Add ("short-" + i, i, cip); } Assert.AreEqual (200, mc.GetCount (), "#CEO3"); global::System.Threading.Thread.Sleep (4 * 1000); Assert.AreEqual (100, mc.GetCount (), "#CEO4"); } }
public void TestExpiredGetValues () { var config = new NameValueCollection (); config["cacheMemoryLimitMegabytes"] = 0.ToString (); config["physicalMemoryLimitPercentage"] = 100.ToString (); config["__MonoEmulateOneCPU"] = true.ToString (); // it appears that pollingInterval does nothing, so we set the Mono timer as well config["pollingInterval"] = new TimeSpan (0, 0, 10).ToString (); config["__MonoTimerPeriod"] = 10.ToString (); using (var mc = new MemoryCache ("TestExpiredGetValues", config)) { Assert.AreEqual (0, mc.GetCount (), "#EGV1"); var keys = new List<string> (); // add some short duration entries for (int i = 0; i < 10; i++) { var key = "short-" + i; var expireAt = DateTimeOffset.Now.AddSeconds (1); mc.Add (key, i.ToString (), expireAt); keys.Add (key); } Assert.AreEqual (10, mc.GetCount (), "#EGV2"); global::System.Threading.Thread.Sleep (1000); // we have waited but the items won't be expired by the timer since it wont have fired yet Assert.AreEqual (10, mc.GetCount (), "#EGV3"); // calling GetValues() will expire the items since we are now past their expiresAt mc.GetValues (keys); Assert.AreEqual (0, mc.GetCount (), "#EGV4"); } }
public void TestCacheShrink () { const int HEAP_RESIZE_THRESHOLD = 8192 + 2; const int HEAP_RESIZE_SHORT_ENTRIES = 2048; const int HEAP_RESIZE_LONG_ENTRIES = HEAP_RESIZE_THRESHOLD - HEAP_RESIZE_SHORT_ENTRIES; var config = new NameValueCollection (); config["cacheMemoryLimitMegabytes"] = 0.ToString (); config["physicalMemoryLimitPercentage"] = 100.ToString (); config["__MonoEmulateOneCPU"] = true.ToString (); // it appears that pollingInterval does nothing, so we set the Mono timer as well config["pollingInterval"] = new TimeSpan (0, 0, 1).ToString (); config["__MonoTimerPeriod"] = 1.ToString (); using (var mc = new MemoryCache ("TestCacheShrink", config)) { Assert.AreEqual (0, mc.GetCount (), "#CS1"); // add some short duration entries for (int i = 0; i < HEAP_RESIZE_SHORT_ENTRIES; i++) { var expireAt = DateTimeOffset.Now.AddSeconds (3); mc.Add ("short-" + i, i.ToString (), expireAt); } Assert.AreEqual (HEAP_RESIZE_SHORT_ENTRIES, mc.GetCount (), "#CS2"); // add some long duration entries for (int i = 0; i < HEAP_RESIZE_LONG_ENTRIES; i++) { var expireAt = DateTimeOffset.Now.AddSeconds (12); mc.Add ("long-" + i, i.ToString (), expireAt); } Assert.AreEqual (HEAP_RESIZE_LONG_ENTRIES + HEAP_RESIZE_SHORT_ENTRIES, mc.GetCount(), "#CS3"); // wait for the cache thread to expire the short duration items, this will also shrink the size of the cache global::System.Threading.Thread.Sleep (5 * 1000); Assert.AreEqual (HEAP_RESIZE_LONG_ENTRIES, mc.GetCount (), "#CS4"); // add some new items into the cache, this will grow the cache again for (int i = 0; i < HEAP_RESIZE_LONG_ENTRIES; i++) { mc.Add("final-" + i, i.ToString (), DateTimeOffset.Now.AddSeconds (4)); } Assert.AreEqual (HEAP_RESIZE_LONG_ENTRIES + HEAP_RESIZE_LONG_ENTRIES, mc.GetCount (), "#CS5"); } }
public bool Add <T>(string key, T val, TimeSpan expiresIn) => FBackend.Add(key, val, new CacheItemPolicy { AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration, SlidingExpiration = expiresIn });
public void TestCacheSliding () { var config = new NameValueCollection (); config["cacheMemoryLimitMegabytes"] = 0.ToString (); config["physicalMemoryLimitPercentage"] = 100.ToString (); config["pollingInterval"] = new TimeSpan (0, 0, 1).ToString (); using (var mc = new MemoryCache ("TestCacheSliding", config)) { Assert.AreEqual (0, mc.GetCount (), "#CSL1"); var cip = new CacheItemPolicy(); // The sliding expiration timeout has to be greater than 1 second because // .NET implementation ignores timeouts updates smaller than // CacheExpires.MIN_UPDATE_DELTA which is equal to 1. cip.SlidingExpiration = new TimeSpan (0, 0, 2); mc.Add("slidingtest", "42", cip); mc.Add("expire1", "1", cip); mc.Add("expire2", "2", cip); mc.Add("expire3", "3", cip); mc.Add("expire4", "4", cip); mc.Add("expire5", "5", cip); Assert.AreEqual (6, mc.GetCount (), "#CSL2"); for (int i = 0; i < 50; i++) { global::System.Threading.Thread.Sleep (100); var item = mc.Get ("slidingtest"); Assert.AreNotEqual (null, item, "#CSL3-" + i); } Assert.IsNull (mc.Get ("expire1"), "#CSL4-1"); Assert.IsNull (mc.Get ("expire2"), "#CSL4-2"); Assert.IsNull (mc.Get ("expire3"), "#CSL4-3"); Assert.IsNull (mc.Get ("expire4"), "#CSL4-4"); Assert.IsNull (mc.Get ("expire5"), "#CSL4-5"); Assert.AreEqual (1, mc.GetCount (), "#CSL4"); global::System.Threading.Thread.Sleep (4 * 1000); Assert.IsNull (mc.Get ("slidingtest"), "#CSL5a"); Assert.AreEqual (0, mc.GetCount (), "#CSL5"); } }
public void TestCacheSliding () { var config = new NameValueCollection (); config["cacheMemoryLimitMegabytes"] = 0.ToString (); config["physicalMemoryLimitPercentage"] = 100.ToString (); config["__MonoEmulateOneCPU"] = true.ToString (); // it appears that pollingInterval does nothing, so we set the Mono timer as well config["pollingInterval"] = new TimeSpan (0, 0, 1).ToString (); config["__MonoTimerPeriod"] = 1.ToString (); using (var mc = new MemoryCache ("TestCacheSliding", config)) { Assert.AreEqual (0, mc.GetCount (), "#CSL1"); var cip = new CacheItemPolicy(); cip.SlidingExpiration = new TimeSpan (0, 0, 1); mc.Add("slidingtest", "42", cip); mc.Add("expire1", "1", cip); mc.Add("expire2", "2", cip); mc.Add("expire3", "3", cip); mc.Add("expire4", "4", cip); mc.Add("expire5", "5", cip); Assert.AreEqual (6, mc.GetCount (), "#CSL2"); for (int i = 0; i < 50; i++) { global::System.Threading.Thread.Sleep (100); var item = mc.Get ("slidingtest"); Assert.AreNotEqual (null, item, "#CSL3-" + i); } Assert.AreEqual (1, mc.GetCount (), "#CSL4"); global::System.Threading.Thread.Sleep (4 * 1000); Assert.AreEqual (0, mc.GetCount (), "#CSL5"); } }
/// <summary> /// Set Key and value on the MemoryCache server cache /// </summary> /// <typeparam name="T">Type of object</typeparam> /// <param name="key">Key of object</param> /// <returns>object</returns> public override void Set <T>(string key, T value) { Cache.Add(key, value, options); }
/// <summary> /// Add new object to the cache /// </summary> /// <param name="key"></param> /// <param name="data"></param> public void SetOnly(string key, object data) { _cache.Add(key, data, DateTimeOffset.UtcNow.AddMinutes(30)); }