Exemplo n.º 1
0
        public void SetAndExists()
        {
            string key    = "6";
            var    result = _redisDatabase.Set(key, "呼吁", TimeSpan.FromSeconds(60));
            //var result = RedisHelper.Set(key, "呼吁", TimeSpan.FromSeconds(60));
            var isExists = _redisDatabase.Exists(key);

            Assert.AreEqual(true, result);
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="keySucceed"></param>
        /// <param name="keyError"></param>
        /// <param name="hitDuration"></param>
        private void RecordRequest(string keySucceed = null, string keyError = null, string hitDuration = "1d")
        {
            if (!string.IsNullOrEmpty(keySucceed))
            {
                if (!_redisManager.Exists(keySucceed))
                {
                    _redisManager.StringIncrement(keySucceed, expiry: _ConvertToTimeSpan(hitDuration));
                }
                else
                {
                    _redisManager.StringIncrement(keySucceed);
                }
            }
            else
            {
                if (!_redisManager.Exists(keyError))
                {
                    _redisManager.StringIncrement(keyError, expiry: _ConvertToTimeSpan(hitDuration));
                }
                else
                {
                    _redisManager.StringIncrement(keyError);
                }
            }

            TimeSpan _ConvertToTimeSpan(string timeSpan)
            {
                var l     = timeSpan.Length - 1;
                var value = timeSpan.Substring(0, l);
                var type  = timeSpan.Substring(l, 1);

                switch (type)
                {
                case "d": return(TimeSpan.FromDays(double.Parse(value)));

                case "h": return(TimeSpan.FromHours(double.Parse(value)));

                case "m": return(TimeSpan.FromMinutes(double.Parse(value)));

                case "s": return(TimeSpan.FromSeconds(double.Parse(value)));

                case "f": return(TimeSpan.FromMilliseconds(double.Parse(value)));

                case "z": return(TimeSpan.FromTicks(long.Parse(value)));

                default: return(TimeSpan.FromDays(double.Parse(value)));
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            var token = context.RequestAborted.Register(async() =>
            {
                await Task.CompletedTask;
                return;
            });

            var analysisConfigListTemp = _requestAnalysisOption.PolicyOption;

            _iLogger.LogDebug($"流量分析获取的请求路径:{context.Request.Path.Value}"); //TODO 支持包含{id}此类路径
            var analysisConfigTemp = analysisConfigListTemp?.Where(s => s.Enabled == true && s.Path.Equals(context.Request.Path.Value, StringComparison.OrdinalIgnoreCase))?.FirstOrDefault();

            int maxLimitTemp      = 0;
            int maxErrorLimitTemp = 0;

            if (analysisConfigTemp == null)
            {
                goto gotoNext;
            }
            if (analysisConfigTemp != null && maxLimitTemp == 0)
            {
                maxLimitTemp = analysisConfigTemp.MaxSucceedLimit;
            }
            if (analysisConfigTemp != null && maxErrorLimitTemp == 0)
            {
                maxErrorLimitTemp = analysisConfigTemp.MaxErrorLimit;
            }
            string path = context.Request.Path.Value.Replace('/', ':');

            string limitkey = $"{RedisKeys.Key_Request_Limit_IP_Lock}{GetRequestIp()}";

            if (!analysisConfigTemp.IsGlobalLock)
            {
                limitkey = limitkey + path;
            }

            if (_redisManager.Exists(limitkey))
            {
                _iLogger.LogWarning($"[Analysic] 触发请求锁定 IsGlobalLock:{analysisConfigTemp.IsGlobalLock}  时长:{analysisConfigTemp.LockDuration} ");
                await BuildErrorJson(context);

                await Task.CompletedTask;
                return;
            }
            var CheckIpValidResultByConfig = CheckIpValid(maxLimitTemp, maxErrorLimitTemp, context.Request.Path.Value.Replace('/', ':'));

            if (!CheckIpValidResultByConfig.Item1)
            {
                //触发限制
                if (!string.IsNullOrWhiteSpace(analysisConfigTemp.LockDuration))
                {
                    _redisManager.GetOrSet($"{limitkey}", () =>
                    {
                        return(context.Request.QueryString.Value);
                    }, _ConvertToTimeSpan(analysisConfigTemp.LockDuration), (int)_ConvertToTimeSpan(analysisConfigTemp.LockDuration).TotalSeconds - 1);
                }

                _iLogger.LogWarning($"[Analysic] 触发请求限制 时长:{analysisConfigTemp.HitDuration} ");
                await BuildErrorJson(context);

                await Task.CompletedTask;
                return;
            }
            else
            {
                await _next(context);

                var currentIp = GetRequestIp();
                if (context.Response.StatusCode == 200)
                {
                    string keySucceed = $"{RedisKeys.Key_Request_Limit_IP_Succ}{currentIp}";
                    RecordRequest(keySucceed: $"{keySucceed}{path}", hitDuration: analysisConfigTemp.HitDuration);
                }
                else
                {
                    string keyError = $"{RedisKeys.Key_Request_Limit_IP_Error}{currentIp}";
                    RecordRequest(keyError: $"{keyError}{path}", hitDuration: analysisConfigTemp.HitDuration);
                }

                await Task.CompletedTask;
                return;
            }
gotoNext:
            await _next(context);
        }