/// <summary>
        /// Helper method which uses the RedisConnectionConfig properties to get the correct RedisConnectionWrapper
        ///     given an HttpContext
        /// </summary>
        /// <param name="context">The httpcontext of the current request</param>
        /// <returns>
        /// A RedisConnectionWrapper object which can be used to get an StackExchange.Redis IDatabase instance
        ///     for communicating with Redis
        /// </returns>
        public static RedisConnectionWrapper RedisConnWrapperFromContext(HttpContextBase context)
        {
            if (RedisConnectionConfig.GetSERedisServerConfigDbIndex != null)
            {
                Tuple <string, int, ConfigurationOptions> connData =
                    RedisConnectionConfig.GetSERedisServerConfigDbIndex(context);
                return(new RedisConnectionWrapper(
                           connData.Item1,
                           connData.Item2,
                           connData.Item3));
            }
            else if (RedisConnectionConfig.GetSERedisServerConfig != null)
            {
                KeyValuePair <string, ConfigurationOptions> connData =
                    RedisConnectionConfig.GetSERedisServerConfig(context);
                return(new RedisConnectionWrapper(
                           connData.Key,
                           connData.Value));
            }
#pragma warning disable 0618
            else if (RedisConnectionConfig.GetRedisServerAddress != null)
            {
                return(new RedisConnectionWrapper(
                           RedisConnectionConfig.GetRedisServerAddress(context)));
            }
#pragma warning restore 0618

            throw new ConfigurationErrorsException(
                      "RedisSessionProvider.Config.RedisConnectionWrapper.GetSERedisServerConfig delegate not set " +
                      "see project page at: github.com/welegan/RedisSessionProvider#configuring-your-specifics");
        }
Ejemplo n.º 2
0
        public CacheRepository(IOptions <RedisConnectionConfig> config)
        {
            _config = config.Value;

            Redis = new RedisDB(_config.Db);
            Redis.Host.AddWriteHost(_config.Host, _config.Port, _config.Ssl).Password = _config.Password;
        }
        /// <summary>
        /// Instantiates a new instance of the RedisSessionStateItemCollection class with data from
        ///     Redis
        /// </summary>
        /// <param name="redisHashData">An array of keys to values from the redis hash</param>
        /// <param name="redisConnName">The name of the connection from the redis connection wrapper</param>
        public RedisSessionStateItemCollection(
            HashEntry[] redisHashData,
            string redisConnName,
            byte constructorSignatureDifferentiator)
        {
            int byteDataTotal = 0;
            int concLevel     = RedisSessionConfig.SessionAccessConcurrencyLevel;

            if (concLevel < 1)
            {
                concLevel = 1;
            }

            int numItems = 0;

            if (redisHashData != null)
            {
                numItems = redisHashData.Length;
            }

            // To match ASP.NET behavior, dictionaries should match keys case insensitively
            this.Items             = new ConcurrentDictionary <string, object>(concLevel, numItems, StringComparer.InvariantCultureIgnoreCase);
            this.SerializedRawData = new ConcurrentDictionary <string, string>(concLevel, numItems, StringComparer.InvariantCultureIgnoreCase);
            if (redisHashData != null)
            {
                foreach (var sessDataEntry in redisHashData)
                {
                    string hashItemKey   = sessDataEntry.Name.ToString();
                    string hashItemValue = sessDataEntry.Value.ToString();

                    if (this.SerializedRawData.TryAdd(
                            hashItemKey,
                            hashItemValue))
                    {
                        this.Items.TryAdd(
                            hashItemKey,
                            new NotYetDeserializedPlaceholderValue());
                    }

                    byteDataTotal += hashItemValue.Length;
                }
            }

            // To match ASP.NET behavior, dictionaries should match keys case insensitively
            this.ChangedKeysDict = new ConcurrentDictionary <string, ActionAndValue>(StringComparer.InvariantCultureIgnoreCase);

            if (byteDataTotal != 0 && !string.IsNullOrEmpty(redisConnName) &&
                RedisConnectionConfig.LogRedisSessionSize != null)
            {
                RedisConnectionConfig.LogRedisSessionSize(redisConnName, byteDataTotal);
            }

            this.cereal = RedisSerializationConfig.SessionDataSerializer;

            if (byteDataTotal > RedisConnectionConfig.MaxSessionByteSize)
            {
                RedisConnectionConfig.RedisSessionSizeExceededHandler(this, byteDataTotal);
            }
        }
Ejemplo n.º 4
0
 public IActionResult Settings(RedisConnectionConfig model)
 {
     _writableOptions.Update(opt =>
     {
         opt.Host = model.Host;
         opt.Port = model.Port;
     });
     return(View());
 }
        private static RedisConnectionWrapper GetConnectionWrapperConfiguredIdServer(HttpContextBase context)
        {
            if (RedisConnectionConfig.GetSERedisServerConfig == null)
            {
                return(null);
            }

            var connData = RedisConnectionConfig.GetSERedisServerConfig(context);

            return(new RedisConnectionWrapper(connData.Key, connData.Value));
        }
        private static RedisConnectionWrapper GetConnectionWrapperConfiguredByIdServerDatabase(HttpContextBase context)
        {
            if (RedisConnectionConfig.GetSERedisServerConfigDbIndex == null)
            {
                return(null);
            }

            var connData = RedisConnectionConfig.GetSERedisServerConfigDbIndex(context);

            return(new RedisConnectionWrapper(connData.Item1, connData.Item2, connData.Item3));
        }
Ejemplo n.º 7
0
        public RedisSessionStateItemCollection(Dictionary <string, byte[]> redisHashData, string redisConnName)
        {
            int byteDataTotal = 0;
            int concLevel     = RedisSessionConfig.SessionAccessConcurrencyLevel;

            if (concLevel < 1)
            {
                concLevel = 1;
            }

            int numItems = 0;

            if (redisHashData != null)
            {
                numItems = redisHashData.Count;
            }

            this.Items             = new ConcurrentDictionary <string, object>(concLevel, numItems);
            this.SerializedRawData = new ConcurrentDictionary <string, string>();
            if (redisHashData != null)
            {
                foreach (var sessDataEntry in redisHashData)
                {
                    if (this.SerializedRawData.TryAdd(
                            sessDataEntry.Key,
                            Encoding.UTF8.GetString(sessDataEntry.Value)))
                    {
                        this.Items.TryAdd(
                            sessDataEntry.Key,
                            new NotYetDeserializedPlaceholderValue());
                    }

                    byteDataTotal += sessDataEntry.Value.Length;
                }
            }

            this.ChangedKeysDict = new ConcurrentDictionary <string, ActionAndValue>();

            if (byteDataTotal != 0 && !string.IsNullOrEmpty(redisConnName) &&
                RedisConnectionConfig.LogRedisSessionSize != null)
            {
                RedisConnectionConfig.LogRedisSessionSize(redisConnName, byteDataTotal);
            }

            this.cereal = RedisSerializationConfig.SessionDataSerializer;

            if (byteDataTotal > RedisConnectionConfig.MaxSessionByteSize)
            {
                RedisConnectionConfig.RedisSessionSizeExceededHandler(this, byteDataTotal);
            }
        }
Ejemplo n.º 8
0
        private static void LogConnectionStatistics(string connName)
        {
            ConnectionMultiplexer conn;

            if (RedisConnectionWrapper.RedisConnections.TryGetValue(connName, out conn))
            {
                long priorPeriodCount = RedisConnectionWrapper.RedisStats.ContainsKey(connName) ? RedisConnectionWrapper.RedisStats[connName] : 0;

                long curCount = conn.GetCounters().Interactive.OperationCount;

                // log the sent commands
                RedisConnectionConfig.LogConnectionActionsCountDel(connName, curCount - priorPeriodCount);

                RedisConnectionWrapper.RedisStats[connName] = curCount;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>

        private ConnectionMultiplexer GetManager()
        {
            ConfigurationOptions configurationOptions = new ConfigurationOptions()
            {
                AllowAdmin         = true,
                Password           = RedisPassword,
                DefaultDatabase    = RedisDefaultDataBase,
                ConnectTimeout     = DefaultConnectTimeout,
                AbortOnConnectFail = false,
                AsyncTimeout       = DefaultAsyncTimeout
            };

            if (RedisConnectionConfig == null || RedisConnectionConfig.Count() <= 0)
            {
                throw new ArgumentNullException("redis链接字符串为null");
            }
            //获取连接的字符串
            var connections = RedisConnectionConfig.ToList();

            connections.ForEach(item =>
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    configurationOptions.EndPoints.Add(item);
                }
            });
            var connect = ConnectionMultiplexer.Connect(configurationOptions);

            //注册如下事件
            connect.ConnectionFailed     += MuxerConnectionFailed;
            connect.ConnectionRestored   += MuxerConnectionRestored;
            connect.ErrorMessage         += MuxerErrorMessage;
            connect.ConfigurationChanged += MuxerConfigurationChanged;
            connect.HashSlotMoved        += MuxerHashSlotMoved;
            connect.InternalError        += MuxerInternalError;

            return(connect);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Instantiates a new instance of the RedisSessionStateItemCollection class with data from
        ///     Redis
        /// </summary>
        /// <param name="redisHashData">An array of keys to values from the redis hash</param>
        /// <param name="redisConnName">The name of the connection from the redis connection wrapper</param>
        public RedisSessionStateItemCollection(HashEntry[] redisHashData, string redisKey)
        {
            int concLevel = Math.Max(RedisSessionConfig.SessionAccessConcurrencyLevel, 1);
            int numItems  = redisHashData != null ? redisHashData.Length : 0;

            Items             = new ConcurrentDictionary <string, object>(concLevel, numItems);
            SerializedRawData = new ConcurrentDictionary <string, string>(concLevel, numItems);
            ChangedKeysDict   = new ConcurrentDictionary <string, ActionAndValue>();
            Serializer        = RedisSerializationConfig.SessionDataSerializer;

            if (numItems > 0)
            {
                int byteDataTotal = 0;
                foreach (var sessDataEntry in redisHashData)
                {
                    string hashItemKey   = sessDataEntry.Name.ToString();
                    string hashItemValue = sessDataEntry.Value.ToString();

                    if (this.SerializedRawData.TryAdd(hashItemKey, hashItemValue))
                    {
                        this.Items.TryAdd(hashItemKey, new NotYetDeserializedPlaceholderValue());
                    }

                    byteDataTotal += hashItemValue.Length;
                }

                if (byteDataTotal > 0 && !string.IsNullOrEmpty(redisKey) && RedisConnectionConfig.LogRedisSessionSize != null)
                {
                    RedisConnectionConfig.LogRedisSessionSize(RedisSessionProvider.Redis.RedisConnectionWrapper.GetConnectionId(redisKey), byteDataTotal);
                }

                if (byteDataTotal > RedisConnectionConfig.MaxSessionByteSize)
                {
                    RedisConnectionConfig.RedisSessionSizeExceededHandler(this, byteDataTotal);
                }
            }
        }
        /// <summary>
        /// Gets the number of redis commands sent and received, and sets the count to 0 so the next time
        ///     we will not see double counts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void GetConnectionsMessagesSent(object sender, ElapsedEventArgs e)
        {
            bool logCount = RedisConnectionConfig.LogConnectionActionsCountDel != null;

            if (logCount)
            {
                foreach (string connName in RedisConnectionWrapper.RedisConnections.Keys.ToList())
                {
                    try
                    {
                        ConnectionMultiplexer conn;
                        if (RedisConnectionWrapper.RedisConnections.TryGetValue(connName, out conn))
                        {
                            long priorPeriodCount = 0;
                            if (RedisConnectionWrapper.RedisStats.ContainsKey(connName))
                            {
                                priorPeriodCount = RedisConnectionWrapper.RedisStats[connName];
                            }

                            ServerCounters counts   = conn.GetCounters();
                            long           curCount = counts.Interactive.OperationCount;

                            // log the sent commands
                            RedisConnectionConfig.LogConnectionActionsCountDel(
                                connName,
                                curCount - priorPeriodCount);

                            RedisConnectionWrapper.RedisStats[connName] = curCount;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Ejemplo n.º 12
0
 public RedisConnectionProvider(RedisConnectionConfig redisConnectionConfig)
 {
     _redisConnectionConfig = redisConnectionConfig;
 }