public void Memcached_Update_ItemNotAdded() { // arrange using (var cache = CacheFactory.Build <RaceConditionTestElement>(settings => { settings.WithUpdateMode(CacheUpdateMode.Full) .WithMemcachedCacheHandle("default") .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(20)); })) { RaceConditionTestElement value; // act Func <bool> act = () => cache.TryUpdate(Guid.NewGuid().ToString(), item => item, out value); // assert act().Should().BeFalse("Item has not been added to the cache"); } }
public void Memcached_RaceCondition_WithoutCasHandling() { // arrange using (var cache = CacheFactory.Build <RaceConditionTestElement>(settings => { settings.WithUpdateMode(CacheUpdateMode.Full) .WithMemcachedCacheHandle("default") .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(20)); })) { cache.Remove("myCounter"); cache.Add("myCounter", new RaceConditionTestElement() { Counter = 0 }); int numThreads = 5; int iterations = 10; int numInnerIterations = 10; // act ThreadTestHelper.Run( () => { for (int i = 0; i < numInnerIterations; i++) { var val = cache.Get("myCounter"); val.Should().NotBeNull(); val.Counter++; cache.Put("myCounter", val); } }, numThreads, iterations); // assert Thread.Sleep(10); var result = cache.Get("myCounter"); result.Should().NotBeNull(); Trace.TraceInformation("Counter increased to " + result.Counter); result.Counter.Should().NotBe(numThreads * numInnerIterations * iterations); } }
public void CacheFactory_Build_WithRedisBackplaneNoBackplaneSource() { // arrange act Action act = () => { var cache = CacheFactory.Build <object>(settings => { settings.WithDictionaryHandle(); settings.WithRedisBackplane("redis"); }); cache.Add("test", "test"); cache.Remove("test"); }; // assert act.ShouldThrow <InvalidOperationException>() .WithMessage("*At least one cache handle must be*"); }
public void CacheManager_Put_InvalidValue() { using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { // arrange act Action act = () => cache.Put("key", null); Action actR = () => cache.Put("key", null, null); // assert act.ShouldThrow<ArgumentException>() .WithMessage("*Parameter name: value"); actR.ShouldThrow<ArgumentException>() .WithMessage("*Parameter name: value"); } }
public void CacheManager_Update_InvalidRegion() { using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { // arrange act Action actR = () => cache.Update("key", null, a => a); Action actRU = () => cache.Update("key", null, a => a, 33); // assert actR.ShouldThrow<ArgumentException>() .WithMessage("*Parameter name: region*"); actRU.ShouldThrow<ArgumentException>() .WithMessage("*Parameter name: region*"); } }
public void CacheManager_Remove_KeyNotAvailable() { // arrange using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { string key = "some key"; // act Func <bool> act = () => cache.Remove(key); Func <bool> actR = () => cache.Remove(key, "region"); // assert act().Should().BeFalse("key should not be present"); actR().Should().BeFalse("key should not be present"); } }
public OutputCacheMiddlewareRealCacheTests() { _loggerFactory = new Mock <IOcelotLoggerFactory>(); _logger = new Mock <IOcelotLogger>(); _loggerFactory.Setup(x => x.CreateLogger <OutputCacheMiddleware>()).Returns(_logger.Object); _regionCreator = new RegionCreator(); var cacheManagerOutputCache = CacheFactory.Build <CachedResponse>("OcelotOutputCache", x => { x.WithDictionaryHandle(); }); _cacheManager = new OcelotCacheManagerCache <CachedResponse>(cacheManagerOutputCache); _downstreamContext = new DownstreamContext(new DefaultHttpContext()); _downstreamContext.DownstreamRequest = new HttpRequestMessage(HttpMethod.Get, "https://some.url/blah?abcd=123"); _next = async context => { //do nothing.. }; _middleware = new OutputCacheMiddleware(_next, _loggerFactory.Object, _cacheManager, _regionCreator); }
public void CacheManager_Add_CacheItem_Positive <T>(T value) { // arrange using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { var key = "my key"; var item = new CacheItem <object>(key, value); // act Action act = () => cache.Add(item); // assert act.ShouldNotThrow(); cache.Get(key).Should().Be(value); } }
protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) { var cacheManagerOutputCache = CacheFactory.Build <CachedResponse>("OcelotOutputCache", x => { x.WithDictionaryHandle(); }); _cacheManager = new OcelotCacheManagerCache <CachedResponse>(cacheManagerOutputCache); services.AddSingleton <ICacheManager <CachedResponse> >(cacheManagerOutputCache); services.AddSingleton <IOcelotCache <CachedResponse> >(_cacheManager); services.AddSingleton <IOcelotLoggerFactory, AspDotNetLoggerFactory>(); services.AddLogging(); services.AddSingleton(_cacheManager); services.AddSingleton(ScopedRepository.Object); services.AddSingleton <IRegionCreator, RegionCreator>(); }
public void Test1() { var cache = CacheFactory.Build("getStartedCache", settings => { settings.WithSystemRuntimeCacheHandle("handleName"); }); cache.Add("keyA", "valueA"); cache.Put("keyB", 23); cache.Put("keyC", new Employee()); cache.Update("keyB", v => 42); Console.WriteLine("KeyA is " + cache.Get("keyA")); // should be valueA Console.WriteLine("KeyB is " + cache.Get("keyB")); // should be 42 Console.WriteLine("KeyC is " + cache.Get("keyC").ToString()); cache.Remove("keyA"); Console.WriteLine("KeyA removed? " + (cache.Get("keyA") == null).ToString()); Console.WriteLine("We are done..."); Console.ReadKey(); }
public void SysRuntime_MemoryCache_Absolute_DoesExpire() { // arrange var key = Guid.NewGuid().ToString(); var item = new CacheItem <object>(key, "something", ExpirationMode.Absolute, new TimeSpan(0, 0, 0, 0, 300)); // act using (var act = CacheFactory.Build(_ => _.WithSystemRuntimeCacheHandle())) { // act act.Add(item); act[key].Should().NotBeNull(); Thread.Sleep(310); // assert act[key].Should().BeNull(); } }
public async Task Redis_ValidateVersion_AddPutGetUpdate() { var configKey = Guid.NewGuid().ToString(); var multi = ConnectionMultiplexer.Connect("localhost"); var cache = CacheFactory.Build <Poco>( s => s .WithRedisConfiguration(configKey, multi) .WithBondCompactBinarySerializer() .WithRedisCacheHandle(configKey)); // don't keep it and also dispose it later (seems appveyor doesn't like too many open connections) RedisConnectionManager.RemoveConnection(multi.Configuration); // act/assert using (multi) using (cache) { var key = Guid.NewGuid().ToString(); var value = new Poco() { Id = 23, Something = "§asdad" }; cache.Add(key, value); await Task.Delay(10); var version = (int)multi.GetDatabase(0).HashGet(key, "version"); version.Should().Be(1); cache.Put(key, value); await Task.Delay(10); version = (int)multi.GetDatabase(0).HashGet(key, "version"); version.Should().Be(2); cache.Update(key, r => { r.Something = "new text"; return(r); }); await Task.Delay(10); version = (int)multi.GetDatabase(0).HashGet(key, "version"); version.Should().Be(3); cache.Get(key).Something.Should().Be("new text"); } }
public void CacheManager_Remove_Positive() { // arrange using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { string key = "some key"; cache.Add(key, "something"); // add something to be removed // act var result = cache.Remove(key); var item = cache[key]; // assert result.Should().BeTrue("key should be present"); item.Should().BeNull(); } }
public void DictionaryHandle_AbsoluteExpires() { using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle() .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMilliseconds(50)); })) { var key = Guid.NewGuid().ToString(); cache.Put(key, "value"); Thread.Sleep(20); cache.Get(key).Should().Be("value"); Thread.Sleep(40); cache.Get(key).Should().BeNull("Should be expired."); } }
public void CacheManager_Configuration_AbsoluteExpires() { using (var cache = CacheFactory.Build("testCache", settings => { settings.WithSystemRuntimeCacheHandle(Guid.NewGuid().ToString()) .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMilliseconds(50)); })) { var key = Guid.NewGuid().ToString(); cache.Put(key, "value"); Thread.Sleep(20); cache.Get(key).Should().Be("value"); Thread.Sleep(40); cache.Get(key).Should().BeNull("Should be expired."); } }
public void BaseCacheHandle_ExpirationInherits_Issue_1() { using (var cache = CacheFactory.Build(settings => { settings.WithSystemRuntimeCacheHandle() .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(10)) .And .WithSystemRuntimeCacheHandle(); })) { cache.Add("something", "stuip"); var handles = cache.CacheHandles.ToArray(); handles[0].GetCacheItem("something").ExpirationMode.Should().Be(ExpirationMode.Absolute); // second cache should not inherit the expiration handles[1].GetCacheItem("something").ExpirationMode.Should().Be(ExpirationMode.None); handles[1].GetCacheItem("something").ExpirationTimeout.Should().Be(default(TimeSpan)); } }
public void CacheManager_MicrosoftMemoryCache() { var cacheManager = CacheFactory.Build(b => { b.WithMicrosoftMemoryCacheHandle(); }); using (cacheManager) { LoopAction(Iterations, () => { cacheManager.Add("TestKey", 123); cacheManager.GetCacheItem("TestKey"); cacheManager.GetOrAdd("GetOrSet_TestKey", (key) => { return(new CacheItem <string>(key, "Hello World")); }); }); } }
public WebClient(string userAgent, string redisConnectionString = null) { if (string.IsNullOrEmpty(redisConnectionString)) { _cache = CacheFactory.Build <CacheModel>(settings => settings .WithUpdateMode(CacheUpdateMode.Up) .WithSystemRuntimeCacheHandle()); } else { _cache = CacheFactory.Build <CacheModel>(settings => settings .WithRedisConfiguration("redisConnectionEsiConnectionLibrary", redisConnectionString) .WithRedisBackplane("redisConnectionEsiConnectionLibrary") .WithUpdateMode(CacheUpdateMode.Up) .WithJsonSerializer() .WithRedisCacheHandle("redisConnectionEsiConnectionLibrary")); } _userAgent = userAgent; }
public void CacheManager_Remove_InvalideKey() { // arrange using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { // act Action act = () => cache.Remove(null); Action actR = () => cache.Remove(null, "region"); // assert act.ShouldThrow<ArgumentException>() .WithMessage("*Parameter name: key"); actR.ShouldThrow<ArgumentException>() .WithMessage("*Parameter name: key"); } }
public void Redis_Extensions_WithClientWithDb() { var configKey = Guid.NewGuid().ToString(); var client = ConnectionMultiplexer.Connect("localhost"); var cache = CacheFactory.Build <string>( s => s .WithJsonSerializer() .WithRedisConfiguration(configKey, client, 23) .WithRedisCacheHandle(configKey)); var handle = cache.CacheHandles.OfType <RedisCacheHandle <string> >().First(); var cfg = RedisConfigurations.GetConfiguration(configKey); Assert.Equal(handle.Configuration.Name, configKey); Assert.Equal(23, cfg.Database); Assert.Equal("localhost:6379", cfg.ConnectionString); // cleanup RedisConnectionManager.RemoveConnection(client.Configuration); client.Dispose(); }
private void TryReconnect() { try { _distributedCache = CacheFactory.Build( s => s .WithJsonSerializer() .WithDictionaryHandle() .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(5)) .And .WithRedisConfiguration("redis", _multiplexer) .WithRedisCacheHandle("redis")); _failedInit = false; } catch (InvalidOperationException e) { _failedInit = true; _distributedEnabled = false; _logger.Exception(e); } }
private static void Main(string[] args) { var cache = CacheFactory.Build("getStartedCache", settings => { settings.WithSystemRuntimeCacheHandle("handleName"); }); cache.Add("keyA", "valueA"); cache.Put("keyB", 23); cache.Update("keyB", v => 42); cache.Update("keyB", v => new { a = 1 }); Console.WriteLine("KeyA is " + cache.Get("keyA")); // should be valueA Console.WriteLine("KeyB is " + cache.Get("keyB")); // should be 42 cache.Remove("keyA"); Console.WriteLine("KeyA removed? " + (cache.Get("keyA") == null).ToString()); Console.WriteLine("We are done..."); Console.ReadKey(); }
public void CacheManager_Put_KeyValue_Positive<T>(T value) { using (var cache = CacheFactory.Build(settings => { settings.WithDictionaryHandle("h1"); })) { // arrange var key = "my key"; // act Action act = () => cache.Put(key, value); Action actRegion = () => cache.Put(key, value, "region"); // assert act.ShouldNotThrow(); actRegion.ShouldNotThrow(); cache.Get(key).Should().Be(value); cache.Get(key, "region").Should().Be(value); } }
public static ICacheManager <object> CreateRedisCache(int database = 0, bool sharedRedisConfig = true) { var redisKey = sharedRedisConfig ? "redisConfig" : Guid.NewGuid().ToString(); var cache = CacheFactory.Build(settings => { settings .WithMaxRetries(100) .WithRetryTimeout(1000) .WithRedisConfiguration(redisKey, config => { config .WithDatabase(database) .WithEndpoint(RedisHost, RedisPort); }) ////.WithRedisBackplane(redisKey) .WithRedisCacheHandle(redisKey, true) .EnableStatistics(); }); return(cache); }
public static ICacheManager <T> CreateRedisCache <T>(int database = 0, bool sharedRedisConfig = true) { var redisKey = sharedRedisConfig ? "redisConfig" : Guid.NewGuid().ToString(); var cache = CacheFactory.Build <T>(settings => { settings .WithMaxRetries(100) .WithRetryTimeout(1000) .WithRedisConfiguration(redisKey, config => { config .WithDatabase(database) .WithEndpoint("127.0.0.1", 6379); }) .WithRedisBackPlate(redisKey) .WithRedisCacheHandle(redisKey, true) .EnableStatistics(); }); return(cache); }
public void Expiration_UnableToResetToNone() { using (var cache = CacheFactory.Build <string>( s => s .WithDictionaryHandle() .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromDays(10)))) { var key = Guid.NewGuid().ToString(); cache.Add(key, "value"); cache.Get(key).Should().Be("value"); cache.GetCacheItem(key).ExpirationMode.Should().Be(ExpirationMode.Sliding); var item = cache.GetCacheItem(key); var newItem = item.WithNoExpiration(); cache.Put(newItem); cache.GetCacheItem(key).ExpirationMode.Should().Be(ExpirationMode.None); } }
public void Events_MockedCustomRemove_TestMultiLevelA() { using (var cache = CacheFactory.Build <string>( s => s.WithHandle(typeof(CustomRemoveEventTestHandle)) .And.WithHandle(typeof(CustomRemoveEventTestHandle)) .And.WithHandle(typeof(CustomRemoveEventTestHandle)))) { int?level = null; cache.OnRemoveByHandle += (sender, args) => { level = args.Level; }; // tests if triggereing the first one really triggers the correct level var handle = cache.CacheHandles.OfType <CustomRemoveEventTestHandle>().First(); handle.TestTrigger("key", null, CacheItemRemovedReason.Expired); level.Should().Be(1); } }
private static void UnityInjectionExample() { UnityContainer container = new UnityContainer(); container.RegisterType <ICacheManager <object> >( new ContainerControlledLifetimeManager(), new InjectionFactory((c) => CacheFactory.Build(s => s.WithDictionaryHandle()))); container.RegisterType <UnityInjectionExampleTarget>(); // resolving the test target object should also resolve the cache instance var target = container.Resolve <UnityInjectionExampleTarget>(); target.PutSomethingIntoTheCache(); // our cache manager instance should still be there so should the object we added in the // previous step. var checkTarget = container.Resolve <UnityInjectionExampleTarget>(); checkTarget.GetSomething(); }
public static ICacheManager <object> CreateRedisAndDicCacheWithBackplane(int database = 0, bool sharedRedisConfig = true, string channelName = null, Serializer serializer = Serializer.Proto, bool useLua = true) { var redisKey = sharedRedisConfig ? "redisConfig" + database : Guid.NewGuid().ToString(); var cache = CacheFactory.Build(settings => { settings .WithUpdateMode(CacheUpdateMode.Up) .WithDictionaryHandle() .EnableStatistics(); settings .WithMaxRetries(int.MaxValue) .TestSerializer(serializer) .WithRetryTimeout(1000) .WithRedisConfiguration(redisKey, config => { config .WithAllowAdmin() .WithDatabase(database) .WithEndpoint(RedisHost, RedisPort); }) .WithRedisCacheHandle(redisKey, true) .EnableStatistics(); if (channelName != null) { settings.WithRedisBackplane(redisKey, channelName); } else { settings.WithRedisBackplane(redisKey); } }); foreach (var h in cache.CacheHandles.OfType <RedisCacheHandle <object> >()) { h.UseLua = useLua; } return(cache); }
private static async Task <ICacheManager <object> > CreateAsync(IRedis redis) { if (redis != null && !string.IsNullOrEmpty(redis.ConnectionString)) { var(isConnectionWorks, _) = await redis.IsConnectionWorksAsync(); if (isConnectionWorks) { return(CacheFactory.Build(settings => { settings .WithRedisConfiguration("redis", config => { if (!string.IsNullOrEmpty(redis.Password)) { config.WithPassword(redis.Password); } if (redis.AllowAdmin) { config.WithAllowAdmin(); } config .WithDatabase(redis.Database) .WithEndpoint(redis.Host, redis.Port); }) .WithMaxRetries(1000) .WithRetryTimeout(100) .WithJsonSerializer() .WithRedisBackplane("redis") .WithRedisCacheHandle("redis", true); })); } } return(CacheFactory.Build(settings => settings .WithMicrosoftMemoryCacheHandle() .WithExpiration(ExpirationMode.None, TimeSpan.Zero) )); }