public void AddManager <THub, THubActions>(Action <NotificationOptions> settings) where THub : Hub <THubActions> where THubActions : class { if (!subscribersManagers.ContainsKey(typeof(THubActions))) { NotificationOptions options = new NotificationOptions(new NotificationRoutesTable(), new NotificationControllersTable()); settings(options); if (options.KeyBuilderBuilderType is null) { throw new Exception("You must define a key builder in the extension settings"); } NotificationKeyBuilder keyBuilder = (NotificationKeyBuilder)ActivatorUtilities.CreateInstance(ServiceProvider, options.KeyBuilderBuilderType); NotificationEvents notificationEvents = new NoopNotificationEvents(); if (!(options.NotificationEventsType is null)) { notificationEvents = (NotificationEvents)ActivatorUtilities.CreateInstance(ServiceProvider, options.NotificationEventsType); } RedisConnection connection = ServiceProvider.GetRequiredService <IRedisSettingsProvider>().GetConnectionSettings(); RedisConnectionManager connectionManager = new RedisConnectionManager(connection, notificationEvents); RedisManager redisManager = new RedisManager(connectionManager, notificationEvents); NotificationPubSubManager <THub, THubActions> subManager = new NotificationPubSubManager <THub, THubActions>(ServiceProvider, keyBuilder, redisManager, options); subscribersManagers.Add(typeof(THubActions), subManager); } // do not throw exception. This method must be idemponent (no gains in throwing an exception) }
/// <summary> /// redis cluster中重置连接事件 /// </summary> /// <param name="ipPort"></param> /// <returns></returns> private RedisConnection _redisDataBase_OnRedirect(string ipPort) { var cnn = RedisConnectionManager.Get(ipPort); if (cnn != null) { return((RedisConnection)cnn); } else { this.IsConnected = false; this.RedisConfig = new RedisConfig(ipPort, this.RedisConfig.Passwords, this.RedisConfig.ActionTimeOut); if (_debugModel) { _cnn = new RedisConnectionDebug(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut); } else { _cnn = new RedisConnection(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut); } _cnn.OnRedirect += _redisConnection_OnRedirect; _cnn.OnDisconnected += _cnn_OnDisconnected; this.Connect(); RedisConnectionManager.Set(ipPort, _cnn); return(_cnn); } }
public void Ctor_Configuration__Succeeds() { var redis = new RedisConnectionManager("localhost"); var config = NewCacheConfiguration(redis); config.RootNameSpace = "_TestRootNamespace"; config.Serializer = new BinarySerializationProvider(); config.RedisClientConfiguration = new RedisClientConfiguration(config.RedisClientConfiguration.RedisConnectionManagerConnectionManager) { Host = _redisHost, DbNo = _redisDB, TimeoutMilliseconds = 50 }; var cache = new RedisCacheProvider(config); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); // no exception }
/// <summary> /// 建立redis cluster 本地映射 /// </summary> private void GetClusterMap() { var clusterNodes = ClusterNodes; if (clusterNodes != null && clusterNodes.Any()) { foreach (var item in clusterNodes) { if (!RedisConnectionManager.Exsits(item.IPPort)) { var cnn = new RedisConnection(item.IPPort); cnn.OnRedirect += _redisConnection_OnRedirect; cnn.OnDisconnected += _cnn_OnDisconnected; cnn.Connect(); if (!string.IsNullOrEmpty(RedisConfig.Passwords)) { cnn.Auth(RedisConfig.Passwords); } var isMaster = item.IsMaster; cnn.RedisServerType = isMaster ? RedisServerType.ClusterMaster : RedisServerType.ClusterSlave; RedisConnectionManager.Set(item.IPPort, isMaster, cnn); } } } }
protected override CacheConfiguration NewCacheConfiguration(RedisConnectionManager connection) { return(new CacheConfiguration(connection) { Serializer = new MessagePackSerializationProvider() }); }
public void CleanupExpiredKeys_RemovesOldItems() { var redis = new RedisConnectionManager(_redisHost); var client = newRedisClient(redis); var provider = new RedisCacheProvider(redis); client.Remove(new RedisExpiryManager(new CacheConfiguration(redis))._setKey); var expiryManager = new RedisExpiryManager(new CacheConfiguration(redis)); var key1 = "my.expiringkey.1"; var key2 = "my.expiringkey.2"; var key3 = "my.expiringkey.3"; expiryManager.SetKeyExpiry(client, key1, new DateTime(2012, 1, 1, 12, 1, 1)); expiryManager.SetKeyExpiry(client, key2, new DateTime(2015, 1, 1, 12, 1, 2)); expiryManager.SetKeyExpiry(client, key3, new DateTime(2020, 1, 1, 12, 1, 3)); var result = expiryManager.GetExpiredKeys(client, new DateTime(2020, 1, 1, 12, 1, 5)); Assert.IsNotNull(result); Assert.IsTrue(result.Contains(key1), "key 1 should exist"); Assert.IsTrue(result.Contains(key2), "key 2 should exist"); Assert.IsTrue(result.Contains(key3), "key 3 should exist"); Assert.AreEqual(3, result.Count()); expiryManager.RemoveKeyExpiry(client, result); result = expiryManager.GetExpiredKeys(client, new DateTime(2020, 1, 1, 12, 1, 5)); Assert.AreEqual(0, result.Count()); }
public void Redis_UseExistingConnection() { var conConfig = new ConfigurationOptions() { ConnectTimeout = 10000, AbortOnConnectFail = false, ConnectRetry = 10 }; conConfig.EndPoints.Add("localhost:6379"); var multiplexer = ConnectionMultiplexer.Connect(conConfig); var cfg = ConfigurationBuilder.BuildConfiguration( s => s .WithJsonSerializer() .WithRedisConfiguration("redisKey", multiplexer) .WithRedisCacheHandle("redisKey")); RedisConnectionManager.RemoveConnection(multiplexer.Configuration); using (multiplexer) using (var cache = new BaseCacheManager <long>(cfg)) { cache.Add(Guid.NewGuid().ToString(), 12345); } }
[SuppressMessage("ReSharper", "CA2000")]// It's disposed by the IServiceCollection public static IServiceCollection AddRedisCache(this IServiceCollection services, Action <CacheConfig> configAction) { if (configAction == null) { throw new ArgumentNullException(nameof(configAction), "Cannot add the Redis Cache if no Configuration specified"); } var cacheConfig = new CacheConfig(); configAction.Invoke(cacheConfig); if (services.BuildServiceProvider().GetService <IRedisCacheProvider>() == null) { var connectionManager = new RedisConnectionManager( cacheConfig.Host, cacheConfig.Port, cacheConfig.ConnectTimeout, cacheConfig.Password, cacheConfig.AllowAdmin, cacheConfig.SyncTimeout, cacheConfig.UseSsl); services.AddSingleton <IRedisCacheProvider>(_ => new RedisCacheProvider(connectionManager)); } services.TryAddSingleton(typeof(ICache), typeof(RedisCache)); if (cacheConfig.ManuallyProcessExpiredKeys) { services.AddHostedService <RedisExpiryManager>(); } return(services); }
public void ItemExpires_RemovedFromCache() { var redis = new RedisConnectionManager(); // this is just testing the built in expiry var config = new CacheConfiguration(redis); var cache = new RedisCacheProvider(config); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:ItemExpires_RemovedFromCache"; String value = "Hello World!"; DateTime expires = DateTime.Now.AddSeconds(3); string tag1 = "tag1"; string tag2 = "tag2"; cache.Set(key, value, expires, new List<string> { tag1, tag2 }); var result = cache.Get<String>(key); Assert.IsNotNull(result); Assert.AreEqual(value, result); Thread.Sleep(1000); result = cache.Get<String>(key); Assert.IsNotNull(result); Assert.AreEqual(value, result); Thread.Sleep(2500); result = cache.Get<String>(key); Assert.IsNull(result); }
public void AddManager(string publisherName, Action <NotificationPublisherOptions> settings) { if (this.publisherManagers.ContainsKey(publisherName)) { return; } publisherManagers.Add(publisherName, () => { NotificationPublisherOptions options = new NotificationPublisherOptions(new NotificationRoutesTable()); settings(options); RedisConnection connection = ServiceProvider.GetRequiredService <IRedisSettingsProvider>().GetConnectionSettings(); NotificationEvents notificationEvents = new NoopNotificationEvents(); if (!(options.NotificationEventsType is null)) { notificationEvents = (NotificationEvents)ActivatorUtilities.CreateInstance(ServiceProvider, options.NotificationEventsType); } RedisConnectionManager connectionManager = new RedisConnectionManager(connection, notificationEvents); RedisManager redisManager = new RedisManager(connectionManager, notificationEvents); if (options.KeyBuilderBuilderType is null) { throw new Exception("You must define a key builder in the extension settings"); } NotificationKeyBuilder keyBuilder = (NotificationKeyBuilder)ActivatorUtilities.CreateInstance(ServiceProvider, options.KeyBuilderBuilderType); return(new NotificationPublisherClient(keyBuilder, redisManager, options)); });
protected override CacheConfiguration NewCacheConfiguration(RedisConnectionManager connection) { return(new ProtoBuf.CacheConfiguration(connection) { CacheItemFactory = new ProtobufRedisCacheItemFactory() }); }
public void RemoveByTag_ManyItemSingleTag_ReturnsNoValues() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key1 = "TagCacheTests:Add1"; string key2 = "TagCacheTests:Add2"; string key3 = "TagCacheTests:Add3"; String value1 = "Hello World!"; String value3 = "Two"; String value2 = "Three"; DateTime expires = new DateTime(2099, 12, 11); var tags = new List <string> { "another tag" }; cache.Set(key1, value1, expires, tags); cache.Set(key2, value2, expires, tags); cache.Set(key3, value3, expires, tags); var results = cache.GetByTag <String>(tags[0]); Assert.IsNotNull(results); Assert.AreEqual(results.Count, 3); cache.RemoveByTag(tags[0]); results = cache.GetByTag <String>(tags[0]); Assert.IsNull(results); }
public void Get_AddedObject_ReturnsValue() { var redis = new RedisConnectionManager(); var configuration = GetCacheConfiguration(redis); var cache = new RedisCacheProvider(configuration); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; var value = new TestObject() { Foo = "Hello", Bar = "World", Score = 11 }; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); var result = cache.Get <TestObject>(key); Assert.IsNotNull(result); Assert.AreEqual(value.Foo, result.Foo); Assert.AreEqual(value.Bar, result.Bar); Assert.AreEqual(value.Score, result.Score); }
protected override CacheConfiguration NewCacheConfiguration(RedisConnectionManager connection) { return new ProtoBuf.CacheConfiguration(connection) { CacheItemFactory = new ProtobufRedisCacheItemFactory() }; }
protected override CacheConfiguration NewCacheConfiguration(RedisConnectionManager connection) { return new CacheConfiguration(connection) { Serializer = new BinarySerializationProvider() }; }
public void Set_String_Succeeds() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); // no exception }
public void Get_MissingKey_ReturnsNull() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:NoValueHere." + DateTime.Now.Ticks; var result = cache.Get <String>(key); Assert.IsNull(result); }
static void Main(string[] args) { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new ConsoleLogger(); while (true) { Thread.Sleep(1000); } }
public void SetKeyExpiry_SetsValue() { var redis = new RedisConnectionManager(_redisHost); var client = newRedisClient(redis); client.Remove(new RedisExpiryManager(new CacheConfiguration(redis))._setKey); var expiryManager = new RedisExpiryManager(new CacheConfiguration(redis)); var key = "my.expiringkey.1"; expiryManager.SetKeyExpiry(client, key, new DateTime(2012, 1, 1, 12, 1, 1)); }
public static RedisTarget CreateRedisTarget(IConnectionMultiplexer connectionMultiplexer, int db) { var redisConnectionManager = new RedisConnectionManager(connectionMultiplexer, db); var exceptionLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("method", "${exception:format=Method}"), new JsonAttribute("stackTrace", "${exception:format=StackTrace}"), new JsonAttribute("data", "${exception:format=Data}") } }; var requestLayout = new JsonLayout { Attributes = { new JsonAttribute("httpUrl", "${aspnet-request:HTTP_URL}"), new JsonAttribute("httpHost", "${aspnet-request:HTTP_HOST}"), new JsonAttribute("serverName", "${aspnet-request:SERVER_NAME}"), new JsonAttribute("httpUserAgent", "${aspnet-request:HTTP_USER_AGENT}"), new JsonAttribute("httpVersion", "${aspnet-request:HTTP_VERSION}"), new JsonAttribute("https", "${aspnet-request:HTTPS}"), new JsonAttribute("httpMethod", "${aspnet-request:HTTP_METHOD}"), new JsonAttribute("queryString", "${aspnet-request:QUERY_STRING}"), new JsonAttribute("remoteAddress", "${aspnet-request:REMOTE_ADDR}"), new JsonAttribute("user", "${aspnet-user-identity}") } }; var layout = new JsonLayout { Attributes = { new JsonAttribute("time", "${date:universalTime=true:format=yyyy-MM-ddTHH\\:mm\\:ss.fff}"), new JsonAttribute("level", "${uppercase:${level}}"), new JsonAttribute("message", "${message}"), new JsonAttribute("exception", exceptionLayout, false), new JsonAttribute("request", requestLayout, false) } }; return(new RedisTarget(redisConnectionManager) { Name = "redis", DataType = "list", Layout = layout, Key = "log", }); }
public static ConfigurationBuilderCachePart WithRedisConfiguration(this ConfigurationBuilderCachePart part, string configurationKey, IConnectionMultiplexer redisClient, int database = 0) { NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); NotNull(redisClient, nameof(redisClient)); var connectionString = redisClient.Configuration; part.WithRedisConfiguration(configurationKey, connectionString, database); RedisConnectionManager.AddConnection(connectionString, redisClient); return(part); }
public static ParallelQueueProducerOptions <TEntity> UseRedis <TEntity>( this ParallelQueueProducerOptions <TEntity> options, Action <RedisOptions> redisOptions) { options.SetProducer((sp, name) => { RedisOptions ro = new RedisOptions(); redisOptions?.Invoke(ro); ILogger <QueueProducer <TEntity> > logger = sp.GetRequiredService <ILogger <QueueProducer <TEntity> > >(); RedisConnectionManager connManager = sp.GetRequiredService <RedisConnectionManager>(); return(new QueueProducer <TEntity>(name, ro, connManager, logger)); }); return(options); }
/// <summary> /// 使用密码连接到RedisServer /// </summary> /// <returns></returns> public string Connect() { lock (_syncLocker) { if (!IsConnected) { _cnn.Connect(); IsConnected = _cnn.IsConnected; var infoMsg = Info(); if (infoMsg.Contains(RedisConst.NOAuth)) { if (string.IsNullOrEmpty(RedisConfig.Passwords)) { _cnn.Quit(); return(infoMsg); } var authMsg = Auth(RedisConfig.Passwords); if (string.Compare(authMsg, OK, true) != 0) { _cnn.Quit(); return(authMsg); } } } _cnn.OnRedirect += _redisConnection_OnRedirect; _cnn.KeepAlived(() => this.KeepAlive()); var ipPort = RedisConfig.GetIPPort(); var isMaster = this.IsMaster; var isCluster = this.IsCluster; if (isCluster) { _cnn.RedisServerType = isMaster ? RedisServerType.ClusterMaster : RedisServerType.ClusterSlave; GetClusterMap(ipPort); } else { _cnn.RedisServerType = isMaster ? RedisServerType.Master : RedisServerType.Slave; RedisConnectionManager.Set(ipPort, _cnn); } return(OK); } }
public void Get_ExpiredDate_RemovesFromCache() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2000, 12, 11); cache.Set(key, value, expires); var result = cache.Get <String>(key); Assert.IsNull(result); }
public void Get_AddedKey_ReturnsValue() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); var result = cache.Get <String>(key); Assert.IsNotNull(result); Assert.AreEqual(value, result); }
/// <summary> /// 建立redis cluster 本地映射 /// </summary> /// <param name="ipPort"></param> private void GetClusterMap(string ipPort) { var clusterNodes = ClusterNodes; RedisConnectionManager.SetClusterNodes(clusterNodes); foreach (var item in clusterNodes) { if (!RedisConnectionManager.Exsits(item.IPPort)) { var cnn = new RedisConnection(item.IPPort); cnn.Connect(); cnn.RedisServerType = item.IsMaster ? RedisServerType.ClusterMaster : RedisServerType.ClusterSlave; RedisConnectionManager.Set(item.IPPort, cnn); } } }
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 Ctor_Configuration__Fails() { var redis = new RedisConnectionManager("localhost"); var config = NewCacheConfiguration(redis); config.RedisClientConfiguration = new RedisClientConfiguration(redis) { Host = "nohost", TimeoutMilliseconds = 500 }; var cache = new RedisCacheProvider(config); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); Assert.Fail("Exception should be thrown with bad connections"); }
public void GetByTag_SingleItemManyTags_ReturnsSingleValue() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); var tags = new List <string> { "tag1", "tag2", "tag3" }; cache.Set(key, value, expires, tags); var results = cache.GetByTag <String>("tag2"); Assert.IsNotNull(results); Assert.IsTrue(results.Count > 0); }
public void Get_ExpiredDate_RemovesTags() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); var config = NewCacheConfiguration(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; var tag = "remove tag"; DateTime expires = new DateTime(2000, 12, 11); cache.Set(key, value, expires, tag); var test = cache.Get <String>(key); var tagManager = new RedisTagManager(config.CacheItemFactory); var result = tagManager.GetKeysForTag(newRedisClient(), tag); Assert.AreEqual(result.Count(x => x == tag), 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(); }
/// <summary> /// 建立redis cluster 本地映射 /// </summary> /// <param name="ipPort"></param> private void GetClusterMap(string ipPort) { var clusterNodes = ClusterNodes; RedisConnectionManager.SetClusterNodes(clusterNodes); foreach (var item in clusterNodes) { if (!RedisConnectionManager.Exsits(item.IPPort)) { TaskHelper.Start(() => { var cnn = new RedisConnection(item.IPPort); cnn.OnRedirect += _redisConnection_OnRedirect; cnn.OnDisconnected += _cnn_OnDisconnected; cnn.Connect(); cnn.RedisServerType = item.IsMaster ? RedisServerType.ClusterMaster : RedisServerType.ClusterSlave; RedisConnectionManager.Set(item.IPPort, cnn); }); } } }
public void GetExpiredKeys_DateMin_ReturnsNone() { var redis = new RedisConnectionManager(_redisHost); var client = newRedisClient(redis); client.Remove(new RedisExpiryManager(new CacheConfiguration(redis))._setKey); var expiryManager = new RedisExpiryManager(new CacheConfiguration(redis)); var key1 = "my.expiringkey.1"; var key2 = "my.expiringkey.2"; var key3 = "my.expiringkey.3"; expiryManager.SetKeyExpiry(client, key1, new DateTime(2012, 1, 1, 12, 1, 1)); expiryManager.SetKeyExpiry(client, key2, new DateTime(2012, 1, 1, 12, 1, 2)); expiryManager.SetKeyExpiry(client, key3, new DateTime(2012, 1, 1, 12, 1, 3)); var result = expiryManager.GetExpiredKeys(client, new DateTime(2012, 1, 1, 12, 1, 0)); Assert.IsNotNull(result); Assert.AreEqual(0, result.Count()); }
public void GetExpiredKeys_DateMax_ReturnsKeysLessThanDate() { var redis = new RedisConnectionManager(_redisHost); var client = newRedisClient(redis); client.Remove(new RedisExpiryManager(new CacheConfiguration(redis))._setKey); var expiryManager = new RedisExpiryManager(new CacheConfiguration(redis)); var key1 = "my.expiringkey.1"; var key2 = "my.expiringkey.2"; var key3 = "my.expiringkey.3"; expiryManager.SetKeyExpiry(client, key1, new DateTime(2012, 1, 1, 12, 1, 1)); expiryManager.SetKeyExpiry(client, key2, new DateTime(2015, 1, 1, 12, 1, 2)); expiryManager.SetKeyExpiry(client, key3, new DateTime(2020, 1, 1, 12, 1, 3)); var result = expiryManager.GetExpiredKeys(client, new DateTime(2020, 1, 1, 12, 1, 5)); Assert.IsNotNull(result); Assert.IsTrue(result.Contains(key1), "key 1 should exist"); Assert.IsTrue(result.Contains(key2), "key 2 should exist"); Assert.IsTrue(result.Contains(key3), "key 3 should exist"); Assert.AreEqual(3, result.Count()); }
protected abstract CacheConfiguration NewCacheConfiguration(RedisConnectionManager connection);
public void GetByTag_SingleItemManyTags_ReturnsSingleValue() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); var tags = new List<string> { "tag1", "tag2", "tag3" }; cache.Set(key, value, expires, tags); var results = cache.GetByTag<String>("tag2"); Assert.IsNotNull(results); Assert.IsTrue(results.Count > 0); }
public void RemoveByTag_ManyItemSingleTag_ReturnsNoValues() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key1 = "TagCacheTests:Add1"; string key2 = "TagCacheTests:Add2"; string key3 = "TagCacheTests:Add3"; String value1 = "Hello World!"; String value3 = "Two"; String value2 = "Three"; DateTime expires = new DateTime(2099, 12, 11); var tags = new List<string> { "another tag" }; cache.Set(key1, value1, expires, tags); cache.Set(key2, value2, expires, tags); cache.Set(key3, value3, expires, tags); var results = cache.GetByTag<String>(tags[0]); Assert.IsNotNull(results); Assert.AreEqual(results.Count, 3); cache.RemoveByTag(tags[0]); results = cache.GetByTag<String>(tags[0]); Assert.IsNull(results); }
private RedisClient newRedisClient(RedisConnectionManager redis) { return new RedisClient(redis, _redisDB, 5000); }
public void Get_MissingKey_ReturnsNull() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:NoValueHere." + DateTime.Now.Ticks; var result = cache.Get<String>(key); Assert.IsNull(result); }
public void Get_AddedKey_ReturnsValue() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); var result = cache.Get<String>(key); Assert.IsNotNull(result); Assert.AreEqual(value, result); }
public void Get_ExpiredDate_RemovesTags() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); var config = NewCacheConfiguration(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; var tag = "remove tag"; DateTime expires = new DateTime(2000, 12, 11); cache.Set(key, value, expires, tag); var test = cache.Get<String>(key); var tagManager = new RedisTagManager(config.CacheItemFactory); var result = tagManager.GetKeysForTag(newRedisClient(), tag); Assert.AreEqual(result.Count(x => x == tag), 0); }
public void ItemExpires_Tag_RemovedFromCache() { // this is testing that when expiry happens, the events kick in and remove the tags // see RedisExpireHandler var redis = new RedisConnectionManager(); var config = new CacheConfiguration(redis); var cache = new RedisCacheProvider(config); var client = newRedisClient(config.RedisClientConfiguration); cache.Logger = new TestRedisLogger(); Console.WriteLine("Start Logger"); string key = "TagCacheTests:ItemExpires_Tag_RemovedFromCache"; String value = "Hello World!"; DateTime expires = DateTime.Now.AddSeconds(3); string tag1 = "tag1001"; string tag2 = "tag1002"; cache.Set(key, value, expires, new List<string>{tag1, tag2}); // first check everything has been set var result = cache.Get<String>(key); Assert.IsNotNull(result); Assert.AreEqual(value, result); var keysForTag1 = client.GetKeysForTag(tag1); Assert.IsNotNull(keysForTag1); Assert.IsTrue(keysForTag1.Any(x => x == key)); var tagsForKey = client.GetTagsForKey(key); Assert.IsNotNull(tagsForKey); Assert.IsTrue(tagsForKey.Any(x => x == tag1)); Assert.IsTrue(tagsForKey.Any(x => x == tag2)); // wait a while Thread.Sleep(1000); // check it has not expired yet result = cache.Get<String>(key); Assert.IsNotNull(result); Assert.AreEqual(value, result); keysForTag1 = client.GetKeysForTag(tag1); Assert.IsNotNull(keysForTag1); Assert.IsTrue(keysForTag1.Any(x => x == key)); tagsForKey = client.GetTagsForKey(key); Assert.IsNotNull(tagsForKey); Assert.IsTrue(tagsForKey.Any(x => x == tag1)); Assert.IsTrue(tagsForKey.Any(x => x == tag2)); // now wait until it should have been removed Thread.Sleep(2500); // now check its all been removed result = cache.Get<String>(key); Assert.IsNull(result); keysForTag1 = client.GetKeysForTag(tag1); Assert.IsNotNull(keysForTag1); Assert.IsFalse(keysForTag1.Any(x => x == key)); tagsForKey = client.GetTagsForKey(key); Assert.IsNotNull(tagsForKey); Assert.IsFalse(tagsForKey.Any(x => x == tag1)); Assert.IsFalse(tagsForKey.Any(x => x == tag2)); }
protected override CacheConfiguration NewCacheConfiguration(RedisConnectionManager connection) { return new CacheConfiguration(connection); }
public CacheConfiguration(RedisConnectionManager connectionManager) : base(connectionManager) { this.Serializer = new JsonSerializationProvider(); }
public CacheConfiguration(RedisConnectionManager connectionManager) : base(connectionManager) { Serializer = new MessagePackSerializationProvider(); }
public CacheConfiguration(RedisConnectionManager connectionManager) : base(connectionManager) { Serializer = new ProtoBufSerializationProvider(new ProtobufSerializationConfiguration()); CacheItemFactory = new ProtobufRedisCacheItemFactory(); }
public void Get_AddedObject_ReturnsValue() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; var value = new TestObject() { Foo = "Hello", Bar = "World", Score = 11 }; DateTime expires = new DateTime(2099, 12, 11); cache.Set(key, value, expires); var result = cache.Get<TestObject>(key); Assert.IsNotNull(result); Assert.AreEqual(value.Foo, result.Foo); Assert.AreEqual(value.Bar, result.Bar); Assert.AreEqual(value.Score, result.Score); }
public void Get_ExpiredDate_RemovesFromCache() { var redis = new RedisConnectionManager(); var cache = new RedisCacheProvider(redis); cache.Logger = new TestRedisLogger(); string key = "TagCacheTests:Add"; String value = "Hello World!"; DateTime expires = new DateTime(2000, 12, 11); cache.Set(key, value, expires); var result = cache.Get<String>(key); Assert.IsNull(result); }