public void CacheEntryOptionsDefaultToEmpty() { var opts = new CacheEntryOptions(); Assert.Null(opts.Size); Assert.Null(opts.Timeout); }
public void GetOrCreate_CallsFaultyFactoryOnce() { // Arrange var key = Guid.NewGuid().ToString(); var options = new CacheEntryOptions(TimeSpan.FromMilliseconds(1)); var factoryCallCount = 0; Func <string, AClass> factory = _ => { factoryCallCount++; throw new Exception(); }; var cache = Substitute.For <ICache>(); cache.Get(key, typeof(AClass)).Returns((AClass)null); cache.When(c => c.GetOrCreate(key, typeof(AClass), options, Arg.Any <Func <string, AClass> >())) .Do(c => c.Arg <Func <string, AClass> >()(key)); var logger = Substitute.For <ILogger <ExceptionHandlingCacheDecorator> >(); var decorator = new ExceptionHandlingCacheDecorator(cache, logger); // Act / Assert Assert.Throws <Exception>(() => decorator.GetOrCreate(key, typeof(AClass), options, factory)); Assert.AreEqual(1, factoryCallCount); }
public void GetOrCreateGeneric_ReturnsCachedValue() { // Arrange var key = Guid.NewGuid().ToString(); var cachedValue = new AClass(); Func <string, AClass> factory = _ => new AClass(); var options = new CacheEntryOptions(TimeSpan.FromMilliseconds(1)); var cache = Substitute.For <ICache>(); cache.GetIfCached(key, out Arg.Any <AClass>()).Returns(x => { x[1] = cachedValue; return(true); }); cache.GetOrCreate(key, options, Arg.Any <Func <string, AClass> >()).Returns(cachedValue); cache.Get(key, typeof(AClass)).Returns(cachedValue); var logger = Substitute.For <ILogger <ExceptionHandlingCacheDecorator> >(); var decorator = new ExceptionHandlingCacheDecorator(cache, logger); // Act var result = decorator.GetOrCreate(key, options, factory); // Assert Assert.AreEqual(cachedValue, result); }
public async Task GetOrCreateAsync_ReturnsCachedValue() { // Arrange var key = Guid.NewGuid().ToString(); var cachedValue = new AClass(); Func <string, Task <AClass> > factory = _ => Task.FromResult(new AClass()); var options = new CacheEntryOptions(TimeSpan.FromMilliseconds(1)); var cache = Substitute.For <ICache>(); cache.GetIfCachedAsync <AClass>(key).Returns((true, cachedValue)); cache.GetAsync <AClass>(key).Returns(cachedValue); cache.GetOrCreateAsync(key, options, Arg.Any <Func <string, Task <AClass> > >()).Returns(cachedValue); var logger = Substitute.For <ILogger <ExceptionHandlingCacheDecorator> >(); var decorator = new ExceptionHandlingCacheDecorator(cache, logger); // Act var result = await decorator.GetOrCreateAsync(key, options, factory); // Assert Assert.AreEqual(cachedValue, result); }
public virtual Task Set(string key, ICachable value, CacheEntryOptions entryOptions) { Condition.Requires(key, nameof(key)).IsNotNullOrEmpty(); Condition.Requires(value, nameof(value)).IsNotNull(); Condition.Requires(entryOptions, nameof(entryOptions)).IsNotNull(); _syncClearLock.EnterReadLock(); try { if (CheckSize(value)) { var memoryCacheEntryOptions = CreateMemoryCacheEntryOptions(entryOptions); Interlocked.Add(ref _memoryUsed, value.SizeInBytes); Interlocked.Increment(ref _itemsCount); _memoryCache.Set(key, value, memoryCacheEntryOptions); _logger.LogDebug("{Operation} => key : {Key} | value : {Value}", "set", key, value.Value); } else { _logger.LogWarning("{CacheStore} Cache is full, cannot add item ({Key}) to cache.", Name, key); } } finally { _syncClearLock.ExitReadLock(); } return(CompletedTask); }
public void Create_Arguments_Not_Allow_Null_Or_White_Space(string name, string optionsIndicator) { CacheEntryOptions options = optionsIndicator == null ? null : new CacheEntryOptions(); var factory = new MemoryCacheFactory(new FoobarCache()); Assert.ThrowsAny <ArgumentException>(() => factory.Create(name, options)); }
public async Task SetAsync(string key, TValue value, CacheEntryOptions options = null, CancellationToken ct = default) { this.ValidateKey(key); this.ValidateValue(value); ct.ThrowIfCancellationRequested(); await this.ConnectAsync(ct).ConfigureAwait(false); await this.m_networkLock.WaitAsync(ct).ConfigureAwait(false); try { var rvalue = this.Serialize(value); if (options?.Timeout != null) { await this.m_database.StringSetAsync(key, rvalue, options.Timeout).ConfigureAwait(false); } else { await this.m_database.StringSetAsync(key, rvalue).ConfigureAwait(false); } } finally { this.m_networkLock.Release(); } }
private static async Task ValidateTimeout() { var opts = new DistributedCacheOptions { Configuration = new ConfigurationOptions { EndPoints = { { "127.0.0.1", 6379 } }, ClientName = "dbg-client" } }; var cache = new RedisCache <TestData>(opts); var data = new TestData { LongValue = 10000, StrValue = "Hello, World" }; var options = new CacheEntryOptions { Timeout = TimeSpan.FromSeconds(1) }; await cache.SetAsync("abc", data, options).ConfigureAwait(false); Thread.Sleep(1250); try { await cache.GetAsync("abc").ConfigureAwait(false); throw new SystemException("Key should not be found but is found!"); } catch (ArgumentOutOfRangeException) { } }
public void CanAutomaticallyRemoveTimedoutEntries() { var cache = new MemoryCache <int, int>(); var opts = new CacheEntryOptions { Timeout = TimeSpan.FromMilliseconds(100) }; cache.Add(5, 10, opts); cache.Add(6, 11, opts); opts.Timeout = TimeSpan.FromMilliseconds(5000); cache.Add(10, 20, opts); cache.Add(11, 21, opts); Thread.Sleep(150); cache.ScanForExpiredItems(); cache.RemoveScheduledEntries(); Assert.ThrowsException <KeyNotFoundException>(() => cache[5]); Assert.ThrowsException <KeyNotFoundException>(() => cache[6]); Assert.AreEqual(20, cache[10]); Assert.AreEqual(21, cache[11]); }
public void CacheEntryTimeoutConvertsToMilliseconds() { var opts = new CacheEntryOptions { Timeout = TimeSpan.FromSeconds(5) }; Assert.Equal(5000, opts.GetTimeoutMs()); }
public void CacheEntryTimeoutConvertsToMilliseconds() { var opts = new CacheEntryOptions { Timeout = TimeSpan.FromSeconds(5) }; Assert.AreEqual(5000, opts.Timeout.Value.TotalMilliseconds); }
public void MustGiveSizeOption() { var cache = new MemoryCache <int, string>(10); var options = new CacheEntryOptions(); Assert.ThrowsException <ArgumentException>(() => cache.AddOrUpdate(10, "hello")); Assert.ThrowsException <ArgumentException>(() => cache.AddOrUpdate(10, "hello", options)); }
private DistributedCacheEntryOptions CreateDistributedCacheEntryOptions(CacheEntryOptions entryOptions) { var distributedCacheEntryOptions = new DistributedCacheEntryOptions(); distributedCacheEntryOptions.AbsoluteExpiration = entryOptions.AbsoluteExpiration; distributedCacheEntryOptions.AbsoluteExpirationRelativeToNow = entryOptions.AbsoluteExpirationRelativeToNow; distributedCacheEntryOptions.SlidingExpiration = entryOptions.SlidingExpiration; return(distributedCacheEntryOptions); }
public void WillThrowOnOverflow() { var cache = new MemoryCache <string, string>(10); var opts = new CacheEntryOptions { Size = 15 }; Assert.ThrowsException <ArgumentOutOfRangeException>(() => cache.AddOrUpdate("abc", "def", opts)); Assert.AreEqual(0, cache.Count); Assert.AreEqual(0, cache.Size); }
public void CanUpdateSize() { var cache = new MemoryCache <string, string>(100); var opts = new CacheEntryOptions { Size = 10 }; cache.AddOrUpdate("abc", "def", opts); Assert.AreEqual(1, cache.Count); Assert.AreEqual(10, cache.Size); }
public virtual async Task Set(string key, ICachable value, CacheEntryOptions entryOptions) { Condition.Requires(key, nameof(key)); Condition.Requires(value, nameof(value)); Condition.Requires(entryOptions, nameof(entryOptions)); var distributedCacheEntryOptions = CreateDistributedCacheEntryOptions(entryOptions); var serializedValue = _objectSerializer.Serialize(value.Value); await _redisCache.SetAsync(key, serializedValue, distributedCacheEntryOptions); _logger.LogDebug("{Operation} => key : {Key} | value : {Value}", "set", key, value.Value); }
protected override Task <TreeNode <MenuItem> > BuildAsync(CacheEntryOptions cacheEntryOptions) { var contentRoot = Services.ApplicationContext.ContentRoot; var file = contentRoot.GetFile("/Areas/Admin/sitemap.xml"); var xmlSitemap = new XmlDocument(); xmlSitemap.Load(file.PhysicalPath); var rootNode = ConvertXmlNodeToMenuItemNode(xmlSitemap.DocumentElement.FirstChild as XmlElement); return(Task.FromResult(rootNode)); }
public override Task SetAsync( string key, string obj, int tmo, CancellationToken ct = default ) { var options = new CacheEntryOptions { Timeout = TimeSpan.FromMinutes(tmo) }; return(this._cache.SetAsync(key, obj, options, ct)); }
public async Task SetAsync(string key, string value, CacheEntryOptions options = null, CancellationToken ct = default) { this.ValidateKey(key); ct.ThrowIfCancellationRequested(); if (!this.m_connectionMultiplexer.IsConnected) { await this.ConnectAsync(ct).ConfigureAwait(false); } await this.m_database.StringSetAsync(key, value, null, When.Always, CommandFlags.FireAndForget).ConfigureAwait(false); }
/// <summary> /// Sets the specified key/value pair in the cache. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="cacheEntryOptions">The cache entry options.</param> /// <returns>The value sent in.</returns> public TValue Set <TValue>(object key, TValue value, CacheEntryOptions cacheEntryOptions) { cacheEntryOptions.Tags ??= Array.Empty <string>(); lock (LockObject) { if (cacheEntryOptions.Tags.Length > 0) { TagIndex.Remove(key); TagIndex.Add(key, cacheEntryOptions.Tags.Select(tag => tag.GetHashCode(StringComparison.Ordinal)).ToArray()); } return(SetWithOptions(key, value, cacheEntryOptions)); } }
private MemoryCacheEntryOptions CreateMemoryCacheEntryOptions(CacheEntryOptions entryOptions) { var memoryCacheEntryOptions = new MemoryCacheEntryOptions(); memoryCacheEntryOptions.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = PostEvictionCallback }); memoryCacheEntryOptions.AbsoluteExpiration = entryOptions.AbsoluteExpiration; memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = entryOptions.AbsoluteExpirationRelativeToNow; memoryCacheEntryOptions.SlidingExpiration = entryOptions.SlidingExpiration; return(memoryCacheEntryOptions); }
internal protected override Task SetCoreAsync(string key, object value, CacheEntryOptions options = null) { Guard.ArgumentNotNullOrWhiteSpace(key, nameof(key)); MemoryCacheEntryOptions options2 = options != null ? new MemoryCacheEntryOptions { AbsoluteExpiration = options.AbsoluteExpiration, AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow, SlidingExpiration = options.SlidingExpiration, Priority = (Microsoft.Extensions.Caching.Memory.CacheItemPriority)(int) options.Priority }:_options; _cache.Set(key, value, options2); return(Task.CompletedTask); }
internal protected override ICache Create(string name, CacheEntryOptions options) { Guard.ArgumentNotNullOrWhiteSpace(name, nameof(name)); Guard.ArgumentNotNull(options, nameof(options)); var options2 = new DistributedCacheEntryOptions { AbsoluteExpiration = options.AbsoluteExpiration, AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow, SlidingExpiration = options.SlidingExpiration }; return(new DistributedCache(name, _cache, _serializer, options2)); }
public override Task SetAsync( string key, string obj, int tmo, CancellationToken ct = default ) { var options = new CacheEntryOptions { Timeout = TimeSpan.FromMinutes(tmo) }; this.m_cache.AddOrUpdate(key, obj, options); return(Task.CompletedTask); }
public void SetAsync_HandlesException() { // Arrange var key = Guid.NewGuid().ToString(); var value = new AClass(); var options = new CacheEntryOptions(TimeSpan.FromMilliseconds(1)); var cache = Substitute.For <ICache>(); cache.SetAsync(key, value, options).Throws <Exception>(); var logger = Substitute.For <ILogger <ExceptionHandlingCacheDecorator> >(); var decorator = new ExceptionHandlingCacheDecorator(cache, logger); // Act / Assert Assert.DoesNotThrowAsync(() => decorator.SetAsync(key, value, options)); }
internal protected override ICache Create(string name, CacheEntryOptions options) { Guard.ArgumentNotNullOrWhiteSpace(name, nameof(name)); Guard.ArgumentNotNull(options, nameof(options)); MemoryCacheEntryOptions options2 = new MemoryCacheEntryOptions { AbsoluteExpiration = options.AbsoluteExpiration, AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow, SlidingExpiration = options.SlidingExpiration, Priority = (Microsoft.Extensions.Caching.Memory.CacheItemPriority)(int) options.Priority }; return(new MemoryCache(name, _cache, options2)); }
private bool TryGetCacheEntryOptions(IInvocation invocation, out CacheEntryOptions cacheEntryOptions) { cacheEntryOptions = null; var cacheAttribute = invocation.MethodInvocationTarget.GetCustomAttribute <CacheAttribute>(); if (cacheAttribute == null) { return(false); } cacheEntryOptions = cacheAttribute.ExpirationType == null ? new CacheEntryOptions(_options.DefaultTtl, _options.DefaultExpirationType) : new CacheEntryOptions(cacheAttribute.Ttl, cacheAttribute.ExpirationType.Value); return(true); }
public void GetOrCreateGeneric_HandlesGetException() { // Arrange var key = Guid.NewGuid().ToString(); var factoryValue = new AClass(); Func <string, AClass> factory = _ => factoryValue; var options = new CacheEntryOptions(TimeSpan.FromMilliseconds(1)); var cache = Substitute.For <ICache>(); cache.Get <AClass>(key).Throws(new Exception()); cache.GetOrCreate(key, options, Arg.Any <Func <string, AClass> >()).Throws(new Exception()); var logger = Substitute.For <ILogger <ExceptionHandlingCacheDecorator> >(); var decorator = new ExceptionHandlingCacheDecorator(cache, logger); // Act var result = decorator.GetOrCreate(key, options, factory); // Assert Assert.AreEqual(factoryValue, result); }
public void GetOrCreate_ReturnsCachedValue() { // Arrange var key = Guid.NewGuid().ToString(); var cachedValue = new AClass(); var options = new CacheEntryOptions(TimeSpan.FromMilliseconds(1)); var cache = Substitute.For <ICache>(); cache.Get(key, typeof(AClass)).Returns(cachedValue); var logger = Substitute.For <ILogger <ExceptionHandlingCacheDecorator> >(); var decorator = new ExceptionHandlingCacheDecorator(cache, logger); // Act var result = decorator.GetOrCreate(key, typeof(AClass), options, _ => null); // Assert Assert.AreEqual(cachedValue, result); }
private static IMemoryCache <string, string> GenerateCache() { var cache = new MemoryCache <string, string>(150); var values = new List <Common.Caching.Abstract.KeyValuePair <string, string> >(); var options = new CacheEntryOptions { Size = 1 }; for (var idx = 0; idx < 100; idx++) { var kvp = new Common.Caching.Abstract.KeyValuePair <string, string> { Key = $"key::{idx}", Value = $"value::{idx}" }; values.Add(kvp); } cache.Add(values, options); return(cache); }