Ejemplo n.º 1
1
 public static ICacheAside CreatePubSubDoubleCache(IConnectionMultiplexer redisConnection, IItemSerializer itemSerializer, TimeSpan? defaultTtl = null)
 {
     var remoteCache = new RedisCache(redisConnection.GetDatabase(), itemSerializer, defaultTtl);
     return new DoubleCache(
       new SubscribingCache(new LocalCache.MemCache(defaultTtl), new RedisSubscriber(redisConnection, remoteCache, itemSerializer)),
       new PublishingCache(remoteCache, new RedisPublisher(redisConnection, itemSerializer)));
 }
        public static Dictionary<string, string> GetMultiplePersonalizationSetting(PersonalizationType type, string id, string keys)
        {
            try
            {
                Dictionary<string, string> PersonalizationSettings = new Dictionary<string, string>();
                RedisCache Redis = new RedisCache(_PersonalizationHost);

                switch (type)
                {
                    case PersonalizationType.Org:
                        PersonalizationSettings = Redis.GetMultipleValuesFromOrgCache(id, keys);
                        break;
                    default:
                        throw new NotImplementedException();
                        break;
                }
                return PersonalizationSettings;
            }
            catch (NotImplementedException ex) { }
            catch (Exception ex)
            {

                // throw;
            }

            return null;
        }
        public void Constructor_should_set_generation_if_it_does_not_exist()
        {
            var cache = new RedisCache("regionName", this.ClientManager);

            var genKey = cache.CacheNamespace.GetGenerationKey();
            Assert.Contains("NHibernate-Cache:regionName", genKey);
            Assert.Equal(1, cache.CacheNamespace.GetGeneration());
        }
Ejemplo n.º 4
0
 static PubSubCacheController()
 {
     var connection = ConnectionMultiplexer.Connect("localhost");
     var serializer = new MsgPackItemSerializer();
     var remoteCache = new RedisCache(connection.GetDatabase(), serializer);
     var _pubSubCache = new DoubleCache.DoubleCache(
         new SubscribingCache(new DoubleCache.LocalCache.MemCache(), new RedisSubscriber(connection, remoteCache, serializer)),
         new PublishingCache(remoteCache, new RedisPublisher(connection, serializer)));
 }
        void Constructor_should_get_current_generation_if_it_already_exists()
        {
            // Distributed caches.
            var cache1 = new RedisCache("regionName", ConnectionMultiplexer, options);
            var cache2 = new RedisCache("regionName", ConnectionMultiplexer, options);

            Assert.Equal(1, cache1.CacheNamespace.GetGeneration());
            Assert.Equal(1, cache2.CacheNamespace.GetGeneration());
        }
        public void Constructor_should_get_current_generation_if_it_already_exists()
        {
            // Distributed caches.
            var cache1 = new RedisCache("regionName", this.ClientManager);
            var cache2 = new RedisCache("regionName", this.ClientManager);

            Assert.Equal(1, cache1.CacheNamespace.GetGeneration());
            Assert.Equal(1, cache2.CacheNamespace.GetGeneration());
        }
Ejemplo n.º 7
0
        public void InvalidateItem_invalidates_item()
        {
            var cache = new RedisCache("localhost:6379");

            cache.PutItem("1", new object(), new[] { "ES1", "ES2" }, TimeSpan.MaxValue, DateTimeOffset.MaxValue);
            cache.InvalidateItem("1");

            object item;
            Assert.False(cache.GetItem("1", out item));
        }
        void Configure_cache_expiration()
        {
            var configuration = new RedisCacheConfiguration("region") { Expiration = TimeSpan.FromMinutes(99) };
            var sut = new RedisCache(configuration, ConnectionMultiplexer, options);

            sut.Put(999, new Person("Foo", 10));

            var cacheKey = sut.CacheNamespace.GetKey(999);
            var expiry = Redis.KeyTimeToLive(cacheKey);
            Assert.InRange(expiry.Value, low: TimeSpan.FromMinutes(98), high: TimeSpan.FromMinutes(99));
        }
        void Get_should_deserialize_data()
        {
            var sut = new RedisCache("region", ConnectionMultiplexer, options);
            sut.Put(999, new Person("Foo", 10));

            var person = sut.Get(999) as Person;

            Assert.NotNull(person);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
Ejemplo n.º 10
0
        public void Item_not_returned_after_sliding_expiration_expired()
        {
            var cache = new RedisCache("localhost:6379");
            var item = new TestObject { Message = "OK" };

            cache.PutItem("key", item, new string[0], TimeSpan.Zero.Subtract(new TimeSpan(10000)), DateTimeOffset.MaxValue);

            object fromCache;
            Assert.False(cache.GetItem("key", out fromCache));
            Assert.Null(fromCache);
        }
        void Put_sets_an_expiration_on_the_item()
        {
            var config = new RedisCacheConfiguration("region") { Expiration = TimeSpan.FromSeconds(30) };
            var sut = new RedisCache(config, ConnectionMultiplexer, options);

            sut.Put(999, new Person("Foo", 10));

            var cacheKey = sut.CacheNamespace.GetKey(999);
            var ttl = Redis.KeyTimeToLive(cacheKey);
            Assert.InRange(ttl.Value, TimeSpan.FromSeconds(29), TimeSpan.FromSeconds(30));
        }
Ejemplo n.º 12
0
        public void Item_not_returned_after_absolute_expiration_expired()
        {
            var cache = new RedisCache("localhost:6379");
            var item = new TestObject { Message = "OK" };

            cache.PutItem("key", item, new string[0], TimeSpan.MaxValue, DateTimeOffset.Now.AddMinutes(-10));

            object fromCache;
            Assert.False(cache.GetItem("key", out fromCache));
            Assert.Null(fromCache);
        }
        void Put_adds_the_item_to_the_cache()
        {
            var sut = new RedisCache("region", ConnectionMultiplexer, options);

            sut.Put(999, new Person("Foo", 10));

            var cacheKey = sut.CacheNamespace.GetKey(999);
            var data = Redis.StringGet(cacheKey);
            var person = (Person)options.Serializer.Deserialize(data);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
        void Configure_cache_lock_timeout()
        {
            var configuration = new RedisCacheConfiguration("region") { LockTimeout = TimeSpan.FromSeconds(123) };
            var sut = new RedisCache(configuration, ConnectionMultiplexer, options);
            const string key = "123";
            
            sut.Lock(key);
            var lockKey = sut.CacheNamespace.GetLockKey(key);

            var expiry = Redis.KeyTimeToLive(lockKey);
            Assert.InRange(expiry.Value, low: TimeSpan.FromSeconds(120), high: TimeSpan.FromSeconds(123));
        }
        void Configure_region_expiration_from_config_element()
        {
            var configElement = new RedisCacheElement("region", TimeSpan.FromMinutes(99));
            var props = new Dictionary<string, string>();
            var sut = new RedisCache("region", props, configElement, ConnectionMultiplexer, options);

            sut.Put(999, new Person("Foo", 10));

            var cacheKey = sut.CacheNamespace.GetKey(999);
            var expiry = Redis.KeyTimeToLive(cacheKey);
            Assert.InRange(expiry.Value, low: TimeSpan.FromMinutes(98), high: TimeSpan.FromMinutes(99));
        }
Ejemplo n.º 16
0
 public void EnsureRedisWork()
 {
     RedisCache cache = new RedisCache();
     string key = "now";
     DateTime dt = cache.Get<DateTime>(key);
     if (dt == DateTime.MinValue)
     {
         dt = DateTime.Now;
         cache.Set(key, dt, TimeSpan.FromMinutes(10));
     }
     DateTime dt1 = cache.Get<DateTime>(key);
     Console.WriteLine(dt);
     Console.WriteLine(dt1);
 }
Ejemplo n.º 17
0
        public void Item_cached()
        {
            var cache = new RedisCache("localhost:6379");
            var item = new TestObject { Message = "OK" };

            cache.PutItem("key", item, new string[0], TimeSpan.MaxValue, DateTimeOffset.MaxValue);

            object fromCache;

            Assert.True(cache.GetItem("key", out fromCache));
            Assert.Equal(item.Message, ((TestObject)fromCache).Message);

            Assert.True(cache.GetItem("key", out fromCache));
            Assert.Equal(item.Message, ((TestObject)fromCache).Message);
        }
        void Put_should_retry_until_generation_matches_the_server()
        {
            var sut = new RedisCache("region", ConnectionMultiplexer, options);

            // Another client incremented the generation.
            Redis.StringIncrement(sut.CacheNamespace.GetGenerationKey(), 100);

            sut.Put(999, new Person("Foo", 10));

            Assert.Equal(101, sut.CacheNamespace.GetGeneration());
            var data = Redis.StringGet(sut.CacheNamespace.GetKey(999));
            var person = (Person)options.Serializer.Deserialize(data);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
        public void Configure_region_expiration_from_config_element()
        {
            // Arrange
            var configElement = new RedisCacheElement("region", TimeSpan.FromMinutes(99));
            var props = new Dictionary<string, string>();
            var cache = new RedisCache("region", props, configElement, this.ClientManager);

            // Act
            cache.Put(999, new Person("Foo", 10));

            // Assert
            var cacheKey = cache.CacheNamespace.GlobalCacheKey(999);
            var expiry = Redis.GetTimeToLive(cacheKey);
            Assert.True(expiry >= TimeSpan.FromMinutes(98) && expiry <= TimeSpan.FromMinutes(99));
        }
Ejemplo n.º 20
0
        public void InvalidateSets_invalidate_items_with_given_sets()
        {
            var cache = new RedisCache("localhost:6379");

            cache.PutItem("1", new object(), new[] { "ES1", "ES2" }, TimeSpan.MaxValue, DateTimeOffset.MaxValue);
            cache.PutItem("2", new object(), new[] { "ES2", "ES3" }, TimeSpan.MaxValue, DateTimeOffset.MaxValue);
            cache.PutItem("3", new object(), new[] { "ES1", "ES3", "ES4" }, TimeSpan.MaxValue, DateTimeOffset.MaxValue);
            cache.PutItem("4", new object(), new[] { "ES3", "ES4" }, TimeSpan.MaxValue, DateTimeOffset.MaxValue);

            cache.InvalidateSets(new[] { "ES1", "ES2" });

            object item;
            Assert.False(cache.GetItem("1", out item));
            Assert.False(cache.GetItem("2", out item));
            Assert.False(cache.GetItem("3", out item));
            Assert.True(cache.GetItem("4", out item));
        }
        void Put_should_serialize_item_and_set_with_expiry()
        {
            var sut = new RedisCache("region", ConnectionMultiplexer, options);

            sut.Put(999, new Person("Foo", 10));

            var cacheKey = sut.CacheNamespace.GetKey(999);
            var data = Redis.StringGet(cacheKey);
            var expiry = Redis.KeyTimeToLive(cacheKey);

            Assert.InRange(expiry.Value, low: TimeSpan.FromMinutes(4), high: TimeSpan.FromMinutes(5));

            var person = options.Serializer.Deserialize(data) as Person;
            Assert.NotNull(person);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
        public void Put_should_retry_until_generation_matches_the_server()
        {
            // Arrange
            var cache = new RedisCache("region", this.ClientManager);

            // Another client incremented the generation.
            Redis.Increment(cache.CacheNamespace.GetGenerationKey(), 100);

            // Act
            cache.Put(999, new Person("Foo", 10));

            // Assert
            Assert.Equal(cache.CacheNamespace.GetGeneration(), 101);
            var data = RedisNative.Get(cache.CacheNamespace.GlobalCacheKey(999));
            var person = (Person)serializer.Deserialize(data);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
Ejemplo n.º 23
0
        public void Item_still_returned_after_sliding_expiration_period()
        {
            var cache = new RedisCache("localhost:6379");
            var item = new TestObject { Message = "OK" };

            // Cache the item with a sliding expiration of 10 seconds
            cache.PutItem("key", item, new string[0], TimeSpan.FromSeconds(10), DateTimeOffset.MaxValue);

            object fromCache = null;
            // In a loop of 20 seconds retrieve the item every 5 second seconds.
            for (var i = 0; i < 4; i++)
            {
                Thread.Sleep(5000); // Wait 5 seconds
                // Retrieve item again. This should update LastAccess and as such keep the item 'alive'
                // Break when item cannot be retrieved
                Assert.True(cache.GetItem("key", out fromCache));
            }
            Assert.NotNull(fromCache);
        }
        public void Put_should_serialize_item_and_set_with_expiry()
        {
            // Arrange
            var cache = new RedisCache("region", this.ClientManager);

            // Act
            cache.Put(999, new Person("Foo", 10));

            // Assert
            var cacheKey = cache.CacheNamespace.GlobalCacheKey(999);
            var data = RedisNative.Get(cacheKey);
            var expiry = Redis.GetTimeToLive(cacheKey);

            Assert.True(expiry >= TimeSpan.FromMinutes(4) && expiry <= TimeSpan.FromMinutes(5));

            var person = serializer.Deserialize(data) as Person;
            Assert.NotNull(person);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
Ejemplo n.º 25
0
        static async Task MainAsync()
        {
            var repo = new RandomUser.RandomUserRepository();

            var user = await repo.GetSingleDummyUser();

            Console.WriteLine(string.Format("Fetched user {0} {1}", user.Name.First, user.Name.Last));

            var options = ConfigurationOptions.Parse("localhost");
            options.ClientName = "publishClient";

            var connection = ConnectionMultiplexer.Connect(options);
            var serializer = new MsgPackItemSerializer();
            var remoteCache = new RedisCache(connection.GetDatabase(), serializer);
            var cache = new PublishingCache(remoteCache, new RedisPublisher(connection, serializer));

            cache.Add("/pubsubcache/single", user);

            Console.WriteLine("Published");
            Console.ReadLine();
        }
        public static string GetPersonalizationList(PersonalizationType type, string id, string key, string filter)
        {
            try
            {
                RedisCache Redis = new RedisCache(_PersonalizationHost);
                string Value = null;
                switch (type)
                {
                    case PersonalizationType.Org:
                        Value = Redis.GetListFromOrgCache(id, key, filter);
                        break;
                    default:
                        throw new NotImplementedException();
                        break;
                }

            }
            catch (NotImplementedException ex) {  }
            catch (Exception ex)
            {

            }
            return null;
        }
Ejemplo n.º 27
0
        private static void ConfigureDependencies()
        {
            var cache = new RedisCache();
            cache.InitializeAsync(new Dictionary<string, string>
            {
                {"Endpoint", ConfigurationManager.AppSettings["Redis.Endpoint"]},
                {"Key", ConfigurationManager.AppSettings["Redis.Key"]},
                {"UseSsl", ConfigurationManager.AppSettings["Redis.UseSsl"]}
            });


            var builder = new ContainerBuilder();
            builder.RegisterType<AccountService>().As<IAccountService>().SingleInstance();
            builder.RegisterType<TransfersController>();

            builder.RegisterInstance(cache).As<IAsyncCache>().SingleInstance();
            builder.RegisterInstance(cache).As<ISyncCache>().SingleInstance();

            var container = builder.Build();

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
           
        }
Ejemplo n.º 28
0
 public ViolationsController(CommonContext commonContext, RedisCache redisCache, IServiceProvider serviceProvider, IOptions <AppSettings> appSettings, CommonAccountService commonAccountSvc, ViolationService violationSvc)
     : base(commonContext, redisCache, serviceProvider, appSettings)
 {
     _commonAccountSvc = commonAccountSvc;
     _violationSvc     = violationSvc;
 }
        public void Lock_and_Unlock_concurrently_with_different_cache_clients()
        {
            // Arrange
            var mainCache = new RedisCache("region", this.ClientManager);
            mainCache.Put(1, new Person("Foo", 1));

            var results = new ConcurrentQueue<string>();
            const int numberOfClients = 5;

            // Act
            var tasks = new List<Task>();
            for (var i = 1; i <= numberOfClients; i++)
            {
                int clientNumber = i;
                var t = Task.Factory.StartNew(() =>
                {
                    var cacheX = new RedisCache("region", this.ClientManager);
                    cacheX.Lock(1);
                    results.Enqueue(clientNumber + " lock");

                    // Atrifical concurrency.
                    Thread.Sleep(100);

                    results.Enqueue(clientNumber + " unlock");
                    cacheX.Unlock(1);
                });

                tasks.Add(t);
            }

            // Assert
            Task.WaitAll(tasks.ToArray());

            // Each Lock should be followed by its associated Unlock.
            var listResults = results.ToList();
            for (var i = 1; i <= numberOfClients; i++)
            {
                var lockIndex = listResults.IndexOf(i + " lock");
                Assert.Equal(i + " lock", listResults[lockIndex]);
                Assert.Equal(i + " unlock", listResults[lockIndex + 1]);
            }
        }
Ejemplo n.º 30
0
 public RedisBusiness(ChariotContext _chariotContext,
                      RedisCache distributedCache,
                      IMapper mapper) : base(_chariotContext, distributedCache, mapper)
 {
 }
Ejemplo n.º 31
0
        public void GetItem_validates_parameters()
        {
            object item;

            var unused = new RedisCache("localhost:6379").GetItem(null, out item);
        }
Ejemplo n.º 32
0
        private RedisCache CreateRedisCache()
        {
            var redisCache = new RedisCache(RedisConfiguration.GetRedisConfig());

            return(redisCache);
        }
        public void Get_should_deserialize_data()
        {
            // Arrange
            var cache = new RedisCache("region", this.ClientManager);
            cache.Put(999, new Person("Foo", 10));

            // Act
            var person = cache.Get(999) as Person;

            // Assert
            Assert.NotNull(person);
            Assert.Equal("Foo", person.Name);
            Assert.Equal(10, person.Age);
        }
Ejemplo n.º 34
0
 public ValuesController(RedisCache redisCache)
 {
     _redis = redisCache.GetDatabase();
 }
Ejemplo n.º 35
0
 public AccountActionFilterImpl(CommonContext commonContext, AccountContext accountContext, RedisCache cache, UserService userSvc, CommonAccountService commonAccountSvc, IHostingEnvironment env)
 {
     _cache            = cache;
     _userSvc          = userSvc;
     _commonAccountSvc = commonAccountSvc;
     _env = env;
 }
Ejemplo n.º 36
0
 public UserService(CommonContext commonCtx, RedisCache cache)
 {
     _commonContext = commonCtx;
     _cache         = cache;
 }
Ejemplo n.º 37
0
 public HomeController(CommonContext commonContext, IServiceProvider serviceProvider, RedisCache redisCache, IOptions <AppSettings> appSettings, AccountContext accountCtx, CommonUserService commonUserSvc)
     : base(commonContext, serviceProvider, redisCache, appSettings)
 {
     _commonUserSvc = commonUserSvc;
     _accountCtx    = accountCtx;
 }
 public BaseAccountActionFilterImpl(AccountContext accountCtx, CommonContext commonCtx, RedisCache cache)
 {
     _accountCtx = accountCtx;
     _commonCtx  = commonCtx;
     _cache      = cache;
 }
        void Constructor_should_set_generation_if_it_does_not_exist()
        {
            var cache = new RedisCache("regionName", ConnectionMultiplexer, options);

            var genKey = cache.CacheNamespace.GetGenerationKey();
            Assert.Contains("NHibernate-Cache:regionName", genKey);
            Assert.Equal(1, cache.CacheNamespace.GetGeneration());
        }