internal static CacheBackPlate CreateBackPlate <TCacheValue>(BaseCacheManager <TCacheValue> manager) { NotNull(manager, nameof(manager)); if (manager.Configuration == null) { throw new ArgumentException("Manager's configuration must not be null.", nameof(manager)); } if (manager.Configuration.BackPlateType != null) { if (!manager.CacheHandles.Any(p => p.Configuration.IsBackPlateSource)) { throw new InvalidOperationException("At least one cache handle must be marked as the back plate source."); } try { var backPlate = (CacheBackPlate)Activator.CreateInstance( manager.Configuration.BackPlateType, new object[] { manager.Configuration }); return(backPlate); } catch (TargetInvocationException e) { throw e.InnerException; } } return(null); }
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); } }
public static string C_GETtDBCheckStock(string ptPlantCode) { StringBuilder oSql = new StringBuilder(); try { var tPath = "~/Config/DBStock.json"; var oDBStk = new mlDBStk(); oDBStk = JsonConvert.DeserializeObject <mlDBStk>(File.ReadAllText(HttpContext.Current.Server.MapPath(tPath))); //Memcach init var oMC_Usr = new BaseCacheManager <mlDBStk>(cCNVB.oCMConfig); oMC_Usr.AddOrUpdate("key", oDBStk, _ => oDBStk); oDBStk = oMC_Usr.Get("key"); //Select DB form Brance json var aDB = (from oResultDBStk in oDBStk.DatabaseStock where oResultDBStk.Brance == ptPlantCode.Substring(2, 2) select oResultDBStk).ToList(); oSql.AppendLine("Data Source = " + aDB[0].ServerName + " "); oSql.AppendLine(";Initial Catalog = " + aDB[0].DabaseName + " "); oSql.AppendLine(";Persist Security Info=True;User ID =" + aDB[0].User + " "); oSql.AppendLine(";Password = "******" "); oSql.AppendLine(";Connection Timeout=15;Connection Lifetime=0;Min Pool Size=0;Max Pool Size=30;Pooling=true"); return(oSql.ToString()); } catch (Exception oEx) { throw oEx; } }
public void CacheManager_CtorA_ConfigWithName() { // name should be implicitly set var manager = new BaseCacheManager<object>( ConfigurationBuilder.BuildConfiguration("newName", s => s.WithDictionaryHandle())); manager.Name.Should().Be("newName"); }
private static void InitCache(IEnumerable<CacheManagerConfiguration> configurations) { foreach (var config in configurations) { var cache = new BaseCacheManager<string>(config); caches.Add(cache.Name, new TestItem(cache)); } }
/// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.RazorView" /> class using the view page activator.</summary> /// <param name="controllerContext">The controller context.</param> /// <param name="viewPath">The view path.</param> /// <param name="layoutPath">The layout or master page.</param> /// <param name="runViewStartPages">A value that indicates whether view start files should be executed before the view.</param> /// <param name="viewStartFileExtensions">The set of extensions that will be used when looking up view start files.</param> /// <param name="viewPageActivator">The view page activator.</param> public JsxView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable <string> viewStartFileExtensions, IViewPageActivator viewPageActivator) : base(controllerContext, viewPath, viewPageActivator) { LayoutPath = layoutPath ?? string.Empty; RunViewStartPages = runViewStartPages; ViewStartFileExtensions = viewStartFileExtensions ?? Enumerable.Empty <string>(); _baseCacheManager = ServiceLocator.ServiceProvider.GetService <BaseCacheManager>(); }
private static void MostSimpleCacheManagerB() { var cache = new BaseCacheManager <string>( new CacheManagerConfiguration() .Builder .WithSystemRuntimeCacheHandle() .Build()); }
private static void MostSimpleCacheManagerB() { var cache = new BaseCacheManager<string>( new CacheManagerConfiguration() .Builder .WithSystemRuntimeCacheHandle() .Build()); }
private static void InitCache(IEnumerable <CacheManagerConfiguration> configurations) { foreach (var config in configurations) { var cache = new BaseCacheManager <string>(config); caches.Add(cache.Name, new TestItem(cache)); } }
public CacheAttributeHandler(string keyPrefix) { var config = new ConfigurationBuilder() .WithSystemRuntimeCacheHandle() .Build(); _cache = new BaseCacheManager <object>(config); KeyPrefix = keyPrefix; }
private static void MostSimpleCacheManager() { var config = new ConfigurationBuilder() .WithSystemRuntimeCacheHandle() .Build(); var cache = new BaseCacheManager <string>(config); // or var cache2 = CacheFactory.FromConfiguration <string>(config); }
private static void MostSimpleCacheManager() { var config = new ConfigurationBuilder() .WithSystemRuntimeCacheHandle() .Build(); var cache = new BaseCacheManager<string>(config); // or var cache2 = CacheFactory.FromConfiguration<string>(config); }
private static void MostSimpleCacheManagerWithLogging() { var config = new ConfigurationBuilder() .WithMicrosoftLogging(l => l.AddConsole(LogLevel.Information)) .WithSystemRuntimeCacheHandle() .Build(); var cache = new BaseCacheManager<string>(config); // or var cache2 = CacheFactory.FromConfiguration<string>(config); }
public void UsingExplicitBucketNameWithPassword() { var cacheConfig = new ConfigurationBuilder() .WithCouchbaseConfiguration("cb", new ClientConfiguration()) .WithCouchbaseCacheHandle("cb", "secret-bucket", "secret") // passing in a bucket-name and bucket-password .Build(); var cache = new BaseCacheManager <int>(cacheConfig); cache.AddOrUpdate("test", 1, (v) => v + 1); }
private static void MostSimpleCacheManagerWithLogging() { var config = new ConfigurationBuilder() .WithMicrosoftLogging(l => l.AddConsole(LogLevel.Information)) .WithSystemRuntimeCacheHandle() .Build(); var cache = new BaseCacheManager <string>(config); // or var cache2 = CacheFactory.FromConfiguration <string>(config); }
static void Main(string[] args) { var config = CacheManager.Core.ConfigurationBuilder.BuildConfiguration( s => { s.WithMaxRetries(50); s.WithRetryTimeout(100); s.WithUpdateMode(CacheUpdateMode.Up); s.WithMicrosoftLogging( f => { f.AddDebug(LogLevel.Trace); f.AddConsole(LogLevel.Trace); }); s.WithProtoBufSerializer(); s.WithJsonSerializer(); //s.WithRedisBackplane("redis"); //s.WithRedisConfiguration("redis", // cfg => // cfg.WithEndpoint("127.0.0.1", 6379) // .WithDatabase(0) // .WithAllowAdmin()); s.WithDictionaryHandle("dic1"); s.WithDictionaryHandle("dic2"); s.WithMicrosoftMemoryCacheHandle("ms1"); s.WithSystemRuntimeCacheHandle("runtime1") .EnablePerformanceCounters() .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); //s.WithRedisCacheHandle("redis", true) // .EnablePerformanceCounters() // .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(2)); }); Tests.TestEachMethod(CacheFactory.FromConfiguration<string>(config)); Tests.TestPoco(CacheFactory.FromConfiguration<Poco>(config)); // json test var logConfig = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("cache.json").Build(); var cacheConfig = logConfig.GetCacheConfiguration() .Builder .WithMicrosoftLogging(f => { f.AddDebug(LogLevel.Trace); f.AddConsole(LogLevel.Trace); }) .Build(); var fromJsonCache = new BaseCacheManager<string>(cacheConfig); Tests.TestEachMethod(fromJsonCache); }
public void UsingAppConfig() { // see couchbaseClients/couchbase section in app.config of this project var cacheConfig = new ConfigurationBuilder() .WithCouchbaseCacheHandle("couchbaseClients/couchbase") .Build(); var cache = new BaseCacheManager <int>(cacheConfig); cache.AddOrUpdate("test", 1, (v) => v + 1); }
/// <summary> /// Gets the entries cache. /// </summary> /// <param name="cacheManager">The <see cref="BaseCacheManager"/> used to retieve the internal cache.</param> /// <param name="settings">The settings to operate with.</param> /// <returns></returns> private ICache <EntrySearchCacheKey> GetEntriesCache(BaseCacheManager cacheManager, IWeBlogSettings settings) { var cacheSize = (settings ?? WeBlogSettings.Instance).EntriesCacheSize; if (cacheManager != null) { return(cacheManager.GetNamedInstance <EntrySearchCacheKey>(CacheName, cacheSize, true)); } return(Sitecore.Caching.CacheManager.GetNamedInstance <EntrySearchCacheKey>(CacheName, cacheSize, true)); }
public void SysRuntime_Extensions_Simple() { var cfg = new ConfigurationBuilder().WithSystemRuntimeCacheHandle().Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().NotBeNullOrWhiteSpace(); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); }
public void SysRuntime_Extensions_NamedB() { string name = "instanceName"; var cfg = new ConfigurationBuilder().WithSystemRuntimeCacheHandle(name, true).Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().Be(name); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeTrue(); cache.CacheHandles.Count().Should().Be(1); }
private static void MultiCacheEvictionWithoutRedisCacheHandle() { var config = new ConfigurationBuilder("Redis with Redis Backplane") .WithDictionaryHandle(true) .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(5)) .And .WithRedisBackplane("redisConfig") .WithRedisConfiguration("redisConfig", "localhost,allowadmin=true", enableKeyspaceNotifications: true) //.WithMicrosoftLogging(new LoggerFactory().AddConsole(LogLevel.Debug)) .Build(); var cacheA = new BaseCacheManager <string>(config); var cacheB = new BaseCacheManager <string>(config); var key = "someKey"; cacheA.OnRemove += (s, args) => { Console.WriteLine("A triggered remove: " + args.ToString() + " - key still exists? " + cacheA.Exists(key)); }; cacheB.OnRemove += (s, args) => { Console.WriteLine("B triggered remove: " + args.ToString() + " - key still exists? " + cacheB.Exists(key)); }; cacheA.OnRemoveByHandle += (s, args) => { cacheA.Remove(args.Key); Console.WriteLine("A triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key)); }; cacheB.OnRemoveByHandle += (s, args) => { Console.WriteLine("B triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key) + " in A? " + cacheA.Exists(key)); }; cacheA.OnAdd += (s, args) => { Console.WriteLine("A triggered add: " + args.ToString()); }; cacheB.OnAdd += (s, args) => { Console.WriteLine("B triggered add: " + args.ToString()); }; Console.WriteLine("Add to A: " + cacheA.Add(key, "some value")); Console.WriteLine("Add to B: " + cacheB.Add(key, "some value")); Thread.Sleep(2000); cacheA.Remove(key); }
public void UsingExplicitBucketName() { ClusterHelper.Initialize(); ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password")); var cacheConfig = new ConfigurationBuilder() .WithCouchbaseCacheHandle("keydoesnotmatter", "beer-sample") // passing in a bucket name which should be used .Build(); var cache = new BaseCacheManager <int>(cacheConfig); cache.AddOrUpdate("test", 1, (v) => v + 1); }
public void MsMemory_Extensions_Simple() { var expectedCacheOptions = new MemoryCacheOptions(); var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.First() .ConfigurationTypes.First().ShouldBeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().NotBeNullOrWhiteSpace(); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); var cacheConfig = new CacheManager.Core.ConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build(); var cache = new BaseCacheManager <object>(cacheConfig); var cacheAdapter = new CacheManagerAdapter(cache); var keyStrategy = new HttpStandardKeyStrategy(cacheAdapter); var handler = new HttpCachingHandler(cacheAdapter, keyStrategy); var api = new MyAPI(handler); api.BaseUri = new Uri("http://localhost:3670"); services.AddSingleton <IMyAPI>(api); }
public void MsMemory_Extensions_Simple() { var expectedCacheOptions = new MemoryCacheOptions(); var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build(); var cache = new BaseCacheManager <string>(cfg); // disabling cfg check as they seem to alter the configuration internally after adding it... internal ms bs implementation //cfg.CacheHandleConfigurations.First() // .ConfigurationTypes.First().Should().BeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().NotBeNullOrWhiteSpace(); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); }
public void Redis_UseExistingConnection() { var multiplexer = ConnectionMultiplexer.Connect("localhost:6379"); var cfg = ConfigurationBuilder.BuildConfiguration( s => s .WithJsonSerializer() .WithRedisConfiguration("redisKey", multiplexer) .WithRedisCacheHandle("redisKey")); using (var cache = new BaseCacheManager <long>(cfg)) { cache.Add("somevalue", 12345); } }
public void MsMemory_Extensions_NamedB() { string name = "some instance name"; var expectedCacheOptions = new MemoryCacheOptions(); var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, true).Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.First() .ConfigurationTypes.First().ShouldBeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().Be(name); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeTrue(); cache.CacheHandles.Count().Should().Be(1); }
public async Task Events_OnRemoveExternal_Redis_NoneHandling() { var client = ConnectionMultiplexer.Connect("localhost"); var config = new ConfigurationBuilder() .WithUpdateMode(CacheUpdateMode.None) .WithDictionaryHandle() .And .WithJsonSerializer() .WithRedisConfiguration("redis", client, enableKeyspaceNotifications: true) .WithRedisCacheHandle("redis") .Build(); var key = Guid.NewGuid().ToString(); var onRemoveByHandleValid = false; var onRemoveValid = false; var cache = new BaseCacheManager <int?>(config); cache.OnRemoveByHandle += (s, args) => { if (args.Reason == CacheItemRemovedReason.ExternalDelete && args.Key == key) { onRemoveByHandleValid = true; } }; cache.OnRemove += (s, args) => { if (args.Key == key) { onRemoveValid = true; } }; cache.Add(key, 1234).Should().BeTrue(); var x = cache.Get(key); client.GetDatabase(0).KeyDelete(key); await Task.Delay(1000); onRemoveByHandleValid.Should().BeTrue("onRemoveByHandle Event should have been raised"); onRemoveValid.Should().BeTrue("onRemove Event should have been raised"); cache.CacheHandles.First().Get(key).Should().Be(1234); }
public void UsingAppConfigWithAuthentication() { // see couchbaseClients/couchbase section in app.config of this project // Note: even though we pass in "cb", CacheManager will fall back to the // default couchbase section at couchbaseClients/couchbase! // We could also pass in the section name explicitly instead of "cb". ClusterHelper.Initialize("couchbaseClients/couchbase"); ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password")); var cacheConfig = new ConfigurationBuilder() .WithCouchbaseCacheHandle("keydoesnotmatter") .Build(); var cache = new BaseCacheManager <int>(cacheConfig); cache.AddOrUpdate("test", 1, (v) => v + 1); }
public DbConfigurationCacheFactory(string configurationFileName = "cache.json") { if (string.IsNullOrWhiteSpace(configurationFileName)) { configurationFileName = "cache.json"; } var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile(configurationFileName); var configuration = builder.Build(); var cacheConfiguration = configuration.GetCacheConfiguration() .Builder .WithJsonSerializer() .Build(); CacheManager = new BaseCacheManager <string>(cacheConfiguration); }
public void MsMemory_Extensions_SimpleWithCfg() { var expectedCacheOptions = new MemoryCacheOptions() { Clock = new Microsoft.Extensions.Internal.SystemClock(), CompactOnMemoryPressure = true, ExpirationScanFrequency = TimeSpan.FromSeconds(20) }; var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(expectedCacheOptions).Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.First() .ConfigurationTypes.First().ShouldBeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().NotBeNullOrWhiteSpace(); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); cache.CacheHandles.OfType <MemoryCacheHandle <string> >().First().MemoryCacheOptions.ShouldBeEquivalentTo(expectedCacheOptions); }
private static void CacheUsage() { // initialize all cache instances BaseCacheManager.Initialize(); var timer = new Timer { Interval = new TimeSpan(0, 0, 5).TotalMilliseconds }; timer.Elapsed += (s, ev) => { var cacheResult = SpecificCacheImplementation.Instance.Get(); // get refreshed cache data Console.WriteLine(string.Join(", ", cacheResult)); }; timer.Start(); // something to block main thread Console.ReadKey(); }
public void UsingClusterHelper() { var cfg = new ClientConfiguration() { Servers = new List <Uri>() { new Uri("http://127.0.0.1:8091") } }; ClusterHelper.Initialize(cfg); ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password")); // using cluster helper is enough for CacheManager since 1.0.2 as it falls back to ClusterHelper internally var cacheConfig = new ConfigurationBuilder() .WithCouchbaseCacheHandle("cb") .Build(); var cache = new BaseCacheManager <int>(cacheConfig); cache.AddOrUpdate("test", 1, (v) => v + 1); }
public static void Main(string[] args) { var configBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("cache.json"); var configuration = configBuilder.Build(); ////var cacheCfgf = configuration.GetCacheConfigurations().First(); ////var mgr = new BaseCacheManager<string>(cacheCfgf); int iterations = int.MaxValue; try { var builder = new Core.ConfigurationBuilder("myCache"); builder.WithMicrosoftLogging(f => { f.AddConsole(LogLevel.Warning); f.AddDebug(LogLevel.Debug); }); builder.WithUpdateMode(CacheUpdateMode.Up); builder.WithRetryTimeout(1000); builder.WithMaxRetries(10); //#if NETCORE // builder.WithDictionaryHandle("dic") // .DisableStatistics(); // //Console.WriteLine("Using Dictionary cache handle"); //#else builder.WithDictionaryHandle() .DisableStatistics(); builder.WithRedisCacheHandle("redis", true) .DisableStatistics(); builder.WithRedisBackplane("redis"); builder.WithRedisConfiguration("redis", config => { config .WithAllowAdmin() .WithDatabase(0) .WithConnectionTimeout(5000) //.WithEndpoint("ubuntu-local", 7024); //.WithEndpoint("127.0.0.1", 6380) .WithEndpoint("127.0.0.1", 6379); //.WithEndpoint("192.168.178.34", 7001); }); builder.WithJsonSerializer(); Console.WriteLine("Using Redis cache handle"); //#endif var cacheA = new BaseCacheManager<object>(builder.Build()); cacheA.Clear(); for (int i = 0; i < iterations; i++) { try { Tests.PutAndMultiGetTest(cacheA); } catch (AggregateException ex) { ex.Handle((e) => { Console.WriteLine(e); return true; }); } catch (Exception e) { Console.WriteLine("Error: " + e.Message + "\n" + e.StackTrace); Thread.Sleep(1000); } Console.WriteLine("---------------------------------------------------------"); } } catch (Exception ex) { Console.WriteLine(ex); } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("We are done..."); Console.ForegroundColor = ConsoleColor.Gray; Console.ReadKey(); }
internal static ICollection <BaseCacheHandle <TCacheValue> > CreateCacheHandles <TCacheValue>(BaseCacheManager <TCacheValue> manager, ILoggerFactory loggerFactory, ICacheSerializer serializer) { NotNull(manager, nameof(manager)); NotNull(loggerFactory, nameof(loggerFactory)); var logger = loggerFactory.CreateLogger(nameof(CacheReflectionHelper)); var managerConfiguration = manager.Configuration as ICacheManagerConfiguration; var handles = new List <BaseCacheHandle <TCacheValue> >(); foreach (var handleConfiguration in managerConfiguration.CacheHandleConfigurations) { logger.LogInfo("Creating handle {0} of type {1}.", handleConfiguration.Name, handleConfiguration.HandleType); Type handleType = handleConfiguration.HandleType; Type instanceType = null; ValidateCacheHandleGenericTypeArguments(handleType); // if the configured type doesn't have a generic type definition ( <T> is not // defined ) #if NET40 if (handleType.IsGenericTypeDefinition) #else if (handleType.GetTypeInfo().IsGenericTypeDefinition) #endif { instanceType = handleType.MakeGenericType(new Type[] { typeof(TCacheValue) }); } else { instanceType = handleType; } var instance = CreateInstance( instanceType, new object[] { loggerFactory, serializer, managerConfiguration, manager, handleConfiguration }) as BaseCacheHandle <TCacheValue>; if (instance == null) { throw new InvalidOperationException("Couldn't initialize handle of type " + instanceType.FullName); } handles.Add(instance); } if (handles.Count == 0) { throw new InvalidOperationException("No cache handles defined."); } return(handles); }
public void Main(string[] args) { int iterations = int.MaxValue; try { var builder = new Core.ConfigurationBuilder("myCache"); builder.WithMicrosoftLogging(f => { // TODO: remove after logging upgrade to RC2 f.MinimumLevel = LogLevel.Debug; f.AddConsole(LogLevel.Error); // TODO: change to Debug after logging upgrade to RC2 f.AddDebug(LogLevel.Information); }); builder.WithUpdateMode(CacheUpdateMode.Up); builder.WithRetryTimeout(1000); builder.WithMaxRetries(10); #if DNXCORE50 builder.WithDictionaryHandle("dic") .DisableStatistics(); //Console.WriteLine("Using Dictionary cache handle"); #else builder.WithDictionaryHandle() .DisableStatistics(); builder.WithRedisCacheHandle("redis", true) .DisableStatistics(); builder.WithRedisBackplane("redis"); builder.WithRedisConfiguration("redis", config => { config .WithAllowAdmin() .WithDatabase(0) .WithConnectionTimeout(5000) //.WithEndpoint("ubuntu-local", 7024); .WithEndpoint("127.0.0.1", 6380) .WithEndpoint("127.0.0.1", 6379); //.WithEndpoint("192.168.178.34", 7001); }); builder.WithJsonSerializer(); Console.WriteLine("Using Redis cache handle"); #endif var cacheA = new BaseCacheManager<object>(builder.Build()); cacheA.Clear(); for (int i = 0; i < iterations; i++) { try { Tests.PutAndMultiGetTest(cacheA); } catch (AggregateException ex) { ex.Handle((e) => { Console.WriteLine(e); return true; }); } catch (Exception e) { Console.WriteLine("Error: " + e.Message + "\n" + e.StackTrace); Thread.Sleep(1000); } Console.WriteLine("---------------------------------------------------------"); } } catch (Exception ex) { Console.WriteLine(ex); } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("We are done..."); Console.ForegroundColor = ConsoleColor.Gray; Console.ReadKey(); }
internal static ICollection <BaseCacheHandle <TCacheValue> > CreateCacheHandles <TCacheValue>( BaseCacheManager <TCacheValue> manager, ILoggerFactory loggerFactory, ICacheSerializer serializer) { NotNull(manager, nameof(manager)); NotNull(loggerFactory, nameof(loggerFactory)); var logger = loggerFactory.CreateLogger(nameof(CacheReflectionHelper)); var managerConfiguration = manager.Configuration as ICacheManagerConfiguration; var handles = new List <BaseCacheHandle <TCacheValue> >(); foreach (var handleConfiguration in managerConfiguration.CacheHandleConfigurations) { logger.LogInfo("Creating handle {0} of type {1}.", handleConfiguration.Name, handleConfiguration.HandleType); var handleType = handleConfiguration.HandleType; var requiresSerializer = false; #if !NETSTANDARD requiresSerializer = handleType.GetCustomAttributes(typeof(RequiresSerializerAttribute), false).Any(); #else requiresSerializer = handleType.GetTypeInfo().CustomAttributes.Any(p => p.AttributeType == typeof(RequiresSerializerAttribute)); #endif if (requiresSerializer && serializer == null) { throw new InvalidOperationException($"Cache handle {handleType.FullName} requires serialization of cached values but no serializer has been configured."); } Type instanceType = null; ValidateCacheHandleGenericTypeArguments(handleType); // if the configured type doesn't have a generic type definition ( <T> is not // defined ) #if NET40 if (handleType.IsGenericTypeDefinition) #else if (handleType.GetTypeInfo().IsGenericTypeDefinition) #endif { instanceType = handleType.MakeGenericType(new Type[] { typeof(TCacheValue) }); } else { instanceType = handleType; } var types = new List <object>(new object[] { loggerFactory, managerConfiguration, manager, handleConfiguration }); if (handleConfiguration.ConfigurationTypes.Length > 0) { types.AddRange(handleConfiguration.ConfigurationTypes); } if (serializer != null) { types.Add(serializer); } var instance = CreateInstance(instanceType, types.ToArray()) as BaseCacheHandle <TCacheValue>; if (instance == null) { throw new InvalidOperationException("Couldn't initialize handle of type " + instanceType.FullName); } handles.Add(instance); } if (handles.Count == 0) { throw new InvalidOperationException("No cache handles defined."); } // validate backplane is the last handle in the cache manager (only if backplane is configured) if (handles.Any(p => p.Configuration.IsBackplaneSource) && manager.Configuration.BackplaneType != null) { if (!handles.Last().Configuration.IsBackplaneSource) { throw new InvalidOperationException("The last cache handle should be the backplane source."); } } return(handles); }