示例#1
0
        public void GetOrSet()
        {
            string key    = "GetOrSet";
            var    value  = Guid.NewGuid().ToString();
            var    result = _redisDatabase.GetOrSet <string>(key, () => { return(value); });

            Assert.AreEqual(value, result);
        }
示例#2
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);
        }