Exemple #1
0
        internal static AsyncPolicyWrap <object> GetAsyncFallBackPolicy(
            INHibernateLogger logger,
            AsyncCircuitBreakerPolicy circuitBreaker)
        {
            return(Policy <object>
                   .Handle <BrokenCircuitException>()
                   .Or <Alachisoft.NCache.Runtime.Exceptions.CacheException>(ex =>
                                                                             ex.ErrorCode == NCacheErrorCodes.NO_SERVER_AVAILABLE)
                   .FallbackAsync(
                       fallbackAction:
                       (ctx, ct) =>
            {
                return Task.FromResult((object)null);
            },
                       onFallbackAsync:
                       (res, ctx) =>
            {
                if (logger.IsDebugEnabled())
                {
                    logger.Debug(
                        $"AsyncFallback policy:\n" +
                        $"\tRegion: {ctx["region"]}" +
                        $"\tOperation: {ctx["operation"]}\n" +
                        $"\tFallback result: {res.Result ?? "null"}");
                }

                return Task.CompletedTask;
            }
                       )
                   .WrapAsync(circuitBreaker));
        }
Exemple #2
0
 internal static PolicyWrap <object> GetFallBackPolicy(
     INHibernateLogger logger,
     CircuitBreakerPolicy circuitBreaker)
 {
     return(Policy <object>
            .Handle <BrokenCircuitException>()
            .Or <Alachisoft.NCache.Runtime.Exceptions.CacheException>(ex =>
                                                                      ex.ErrorCode == NCacheErrorCodes.NO_SERVER_AVAILABLE)
            .Fallback <object>(
                fallbackValue:
                null,
                onFallback:
                (res, ctx) =>
     {
         if (logger.IsDebugEnabled())
         {
             logger.Debug(
                 $"Fallback policy:\n" +
                 $"\tRegion: {ctx["region"]}" +
                 $"\tOperation: {ctx["operation"]}\n" +
                 $"\tFallback result: {res.Result ?? "null"}");
         }
     })
            .Wrap(circuitBreaker));
 }
Exemple #3
0
        public TwoLayerCache(TwoLayerCacheConfiguration configuration)
        {
            _log                    = configuration.Log;
            _memoryCache            = configuration.MemoryCache;
            _clientId               = configuration.ClientId;
            _serializer             = configuration.Serializer;
            _database               = configuration.Database;
            _expirationEnabled      = configuration.ExpirationEnabled;
            _useSlidingExpiration   = configuration.UseSlidingExpiration;
            _expiration             = configuration.Expiration;
            _appendAdditionalKeys   = configuration.AppendAdditionalKeys;
            _appendAdditionalValues = configuration.AppendAdditionalValues;
            _redisGet               = configuration.RedisGet;
            _redisGetAsync          = configuration.RedisGetAsync;
            _redisGetMany           = configuration.RedisGetMany;
            _redisGetManyAsync      = configuration.RedisGetManyAsync;
            _putScript              = configuration.PutScript;
            _removeScript           = configuration.RemoveScript;
            _logErrorMessage        = configuration.LogErrorMessage;
            _regionKey              = configuration.RegionKey;
            _usePipelining          = configuration.UsePipelining;
            _maxSynchronizationTime = configuration.MaxSynchronizationTime;

            var connectionMultiplexer = configuration.ConnectionMultiplexer;
            var invalidationChannel   = string.Concat("{", configuration.RegionKey, "}@", "Invalidation");

            _invalidationChannel = invalidationChannel;
            connectionMultiplexer.GetSubscriber().Subscribe(invalidationChannel).OnMessage((Action <ChannelMessage>)OnInvalidationMessage);
            connectionMultiplexer.ConnectionFailed   += OnConnectionFailed;
            connectionMultiplexer.ErrorMessage       += OnErrorMessage;
            connectionMultiplexer.ConnectionRestored += OnConnectionRestored;
        }
 static MemCacheProvider()
 {
     log    = NHibernateLogger.For(typeof(MemCacheProvider));
     config = ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration;
     if (config == null)
     {
         log.Info("enyim.com/memcached configuration section not found, using default configuration (127.0.0.1:11211).");
         config = new MemcachedClientConfiguration();
         config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
     }
 }
Exemple #5
0
 internal static AsyncCircuitBreakerPolicy GetAsyncCircuitBreakerPolicy(
     RegionConfig regionConfig,
     CacheConfig cacheConfig,
     INHibernateLogger logger)
 {
     return(Policy
            .Handle <Alachisoft.NCache.Runtime.Exceptions.CacheException>(ex =>
                                                                          ex.ErrorCode ==
                                                                          NCacheErrorCodes.NO_SERVER_AVAILABLE)
            .CircuitBreakerAsync(
                exceptionsAllowedBeforeBreaking:
                regionConfig.CircuitBreakerExceptionsAllowed,
                durationOfBreak:
                TimeSpan.FromSeconds(
                    regionConfig.CircuitBreakerDurationOfBreak),
                onBreak:
                (ex, ts, ctx) =>
     {
         if (logger.IsDebugEnabled())
         {
             logger.Debug(
                 $"AsyncCircuitbreaker policy:\n" +
                 $"\tRegion: {ctx["region"]}" +
                 $"\tOperation: {ctx["operation"]}" +
                 $"\tCircuit broken for " +
                 $"{cacheConfig.CacheId}\n" +
                 $"\tReason:{ex.Message}");
         }
     },
                onReset: (ctx) =>
     {
         if (logger.IsDebugEnabled())
         {
             logger.Debug(
                 $"AsyncCircuitbreaker policy:\n" +
                 $"\tRegion: {ctx["region"]}" +
                 $"\tCircuit reset for {cacheConfig.CacheId}");
         }
     },
                onHalfOpen: () =>
     {
         if (logger.IsDebugEnabled())
         {
             logger.Debug(
                 $"AsyncCircuitbreaker policy:\n" +
                 $"\tCircuit half-open for" +
                 $" {cacheConfig.CacheId}");
         }
     }
                ));
 }
Exemple #6
0
 /// <summary>
 /// The constructor for creating the region strategy.
 /// </summary>
 /// <param name="connectionMultiplexer">The Redis connection.</param>
 /// <param name="configuration">The region configuration.</param>
 /// <param name="properties">The NHibernate configuration properties.</param>
 protected AbstractRegionStrategy(IConnectionMultiplexer connectionMultiplexer,
                                  RedisCacheRegionConfiguration configuration, IDictionary <string, string> properties)
 {
     Log                   = NHibernateLogger.For(GetType());
     RegionName            = configuration.RegionName;
     Expiration            = configuration.Expiration;
     UseSlidingExpiration  = configuration.UseSlidingExpiration;
     AppendHashcode        = configuration.AppendHashcode;
     RegionKey             = configuration.RegionKey;
     ConnectionMultiplexer = connectionMultiplexer;
     Database              = configuration.DatabaseProvider.Get(connectionMultiplexer, configuration.Database);
     Serializer            = configuration.Serializer;
     LockTimeout           = configuration.LockConfiguration.KeyTimeout;
     _keyLocker            = new RedisKeyLocker(RegionName, Database, configuration.LockConfiguration);
 }
 public static void LogMapped(this Property property, INHibernateLogger log)
 {
     if (log.IsDebugEnabled())
     {
         var msg     = "Mapped property: " + property.Name;
         var columns = string.Join(",", property.Value.ColumnIterator.Select(c => c.Text).ToArray());
         if (columns.Length > 0)
         {
             msg += " -> " + columns;
         }
         var propertyTypeName = SafeGetPropertyTypeName(property);
         if (propertyTypeName != null)
         {
             msg += ", type: " + propertyTypeName;
         }
         log.Debug(msg);
     }
 }
        public static TType GetInstance <TType>(string key, IDictionary <string, string> properties, TType defaultValue,
                                                INHibernateLogger logger)
        {
            var objectsFactory = Cfg.Environment.ObjectsFactory;
            var className      = GetString(key, properties, null);

            System.Type type = null;
            try
            {
                if (className != null)
                {
                    type = ReflectHelper.ClassForName(className);
                    return((TType)objectsFactory.CreateInstance(type));
                }

                // Try to get the instance from the base type if the user provided a custom IObjectsFactory
                if (!(objectsFactory is ActivatorObjectsFactory))
                {
                    try
                    {
                        return((TType)objectsFactory.CreateInstance(typeof(TType)));
                    }
                    catch (Exception e)
                    {
                        // The user most likely did not register the TType
                        logger.Debug(
                            "Failed to create an instance of type '{0}' by using IObjectsFactory, most probably was not registered. Exception: {1}",
                            typeof(TType), e);
                    }
                }

                return(defaultValue);
            }
            catch (Exception e)
            {
                throw new HibernateException(
                          $"Could not instantiate {typeof(TType).Name}: {type?.AssemblyQualifiedName ?? className}", e);
            }
        }
        static MemCacheProvider()
        {
            log = NHibernateLogger.For(typeof(MemCacheProvider));
            var configs = ConfigurationManager.GetSection("memcache") as MemCacheConfig[];

            if (configs != null)
            {
                var myWeights = new ArrayList();
                var myServers = new ArrayList();
                foreach (MemCacheConfig config in configs)
                {
                    myServers.Add(string.Format("{0}:{1}", config.Host, config.Port));
                    log.Debug("adding config for memcached on host {0}", config.Host);
                    if (config.Weight > 0)
                    {
                        myWeights.Add(config.Weight);
                    }
                }
                servers = (string[])myServers.ToArray(typeof(string));
                weights = (int[])myWeights.ToArray(typeof(int));
            }
        }
Exemple #10
0
        public void NewLoggerFactoryTimingsForNoLogging(int iteration)
        {
            ResetCounts();
            NHibernateLogger.SetLoggersFactory((INHibernateLoggerFactory)null);
            INHibernateLogger logger2 = NHibernateLogger.For(this.GetType());

            var stopwatch      = Stopwatch.StartNew();
            var iterationCount = 10000000;

            for (int i = 0; i < iterationCount; i++)
            {
                logger2.Debug("message");
                logger2.Debug("message with parameters {0}, {1}", "string", 5);
            }

            stopwatch.Stop();
            Console.WriteLine(
                "{0} wrote {1:N0} characters to log in {2} ms",
                nameof(NewLoggerFactoryTimingsForDisabledLogging),
                GetCounts(),
                stopwatch.ElapsedMilliseconds);
        }
Exemple #11
0
        static CoreDistributedCacheProvider()
        {
            Log = NHibernateLogger.For(typeof(CoreDistributedCacheProvider));
            ConfiguredCachesProperties = new Dictionary <string, IDictionary <string, string> >();

            if (!(ConfigurationManager.GetSection("coredistributedcache") is CacheConfig config))
            {
                return;
            }

            if (!string.IsNullOrEmpty(config.FactoryClass))
            {
                try
                {
                    var factoryClass       = ReflectHelper.ClassForName(config.FactoryClass);
                    var ctorWithProperties = factoryClass.GetConstructor(CacheFactoryCtorWithPropertiesSignature);

                    CacheFactory = (IDistributedCacheFactory)(ctorWithProperties != null ?
                                                              ctorWithProperties.Invoke(new object[] { config.Properties }):
                                                              Cfg.Environment.ObjectsFactory.CreateInstance(factoryClass));
                }
                catch (Exception e)
                {
                    throw new HibernateException(
                              $"Could not create the {nameof(IDistributedCacheFactory)} factory from '{config.FactoryClass}'. " +
                              $"(It must implement {nameof(IDistributedCacheFactory)} and have a constructor accepting a " +
                              $"{nameof(IDictionary<string, string>)} or have a parameterless constructor.)",
                              e);
                }
            }

            foreach (var cache in config.Regions)
            {
                ConfiguredCachesProperties.Add(cache.Region, cache.Properties);
            }

            AppendHashcodeToKey = config.AppendHashcodeToKey;
        }
Exemple #12
0
        public void OldLoggerFactoryThunkedTimingsForEnabledLogging(int iteration)
        {
            ResetCounts();
            ILoggerFactory loggerFactory = new MockLoggerFactory();

            LoggerProvider.SetLoggersFactory(loggerFactory);
            INHibernateLogger logger2 = NHibernateLogger.For(this.GetType());

            var stopwatch      = Stopwatch.StartNew();
            var iterationCount = 10000000;

            for (int i = 0; i < iterationCount; i++)
            {
                logger2.Warn("message");
                logger2.Warn("message with parameters {0}, {1}", "string", 5);
            }

            stopwatch.Stop();
            Console.WriteLine(
                "{0} wrote {1:N0} characters to log in {2} ms",
                nameof(OldLoggerFactoryThunkedTimingsForEnabledLogging),
                GetCounts(),
                stopwatch.ElapsedMilliseconds);
        }
 public static void Info(this INHibernateLogger logger, string format, params object[] args)
 {
     logger.Log(NHibernateLogLevel.Info, new NHibernateLogValues(format, args), null);
 }
 public static void Warn(this INHibernateLogger logger, Exception exception, string message)
 {
     logger.Log(NHibernateLogLevel.Warn, new NHibernateLogValues(message, null), exception);
 }
 public static void Debug(this INHibernateLogger logger, string message, Exception ex) => ThrowNotImplemented();
 public static bool IsFatalEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Fatal);
 public static bool IsErrorEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Error);
 public static bool IsWarnEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Warn);