コード例 #1
0
        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");
            }
        }
コード例 #2
0
        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);
            }
        }
コード例 #3
0
        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*");
        }
コード例 #4
0
        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");
            }
        }
コード例 #5
0
        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*");
            }
        }
コード例 #6
0
        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");
            }
        }
コード例 #7
0
        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);
        }
コード例 #8
0
        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);
            }
        }
コード例 #9
0
        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>();
        }
コード例 #10
0
ファイル: CMTest.cs プロジェクト: zhanxh/WpfDevDemo
        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();
        }
コード例 #11
0
        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();
            }
        }
コード例 #12
0
        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");
                }
        }
コード例 #13
0
        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();
            }
        }
コード例 #14
0
        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.");
            }
        }
コード例 #15
0
        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.");
            }
        }
コード例 #16
0
        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));
            }
        }
コード例 #17
0
        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"));
                    });
                });
            }
        }
コード例 #18
0
        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;
        }
コード例 #19
0
        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");
            }
        }
コード例 #20
0
        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();
        }
コード例 #21
0
ファイル: CacheProvider.cs プロジェクト: Nazgaul/Spitball
 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);
     }
 }
コード例 #22
0
        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();
        }
コード例 #23
0
        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);
            }
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        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);
        }
コード例 #26
0
            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);
                }
            }
コード例 #27
0
        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);
            }
        }
コード例 #28
0
        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();
        }
コード例 #29
0
        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);
        }
コード例 #30
0
ファイル: CachingUtils.cs プロジェクト: siteserver/Datory
        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)
                                      ));
        }