Exemplo n.º 1
0
        /// <summary>
        /// 判别在规定时间内调用是否超出次数(如:一秒内只能调用3次)
        /// </summary>
        /// <param name="key">检测Key</param>
        /// <param name="timeType">时间类型</param>
        /// <param name="maxCount">最大可调用次数</param>
        /// <returns>true:已经超出次数 false:未超出次数</returns>
        public bool CheckIsOverStep(string key, TimeType timeType, int maxCount)
        {
            CheckHelper.NotEmpty(key, "key");

            if (!timeType.IsInDefined())
            {
                throw new ArgumentException("时间类型不合法!");
            }
            if (maxCount < 0)
            {
                throw new ArgumentException("最大次数必须大于等于0!");
            }

            //缓存Key
            string cacheKey = "IsOverStep:";
            //缓存过期时间
            TimeSpan?expires = null;

            switch (timeType)
            {
            case TimeType.秒:
                string second = DateTime.Now.ToString("yyyyMMddHHmmss");
                cacheKey += $"{key}:{second}";
                expires   = TimeSpan.FromSeconds(10);
                break;

            case TimeType.分:
                string minute = DateTime.Now.ToString("yyyyMMddHHmm");
                cacheKey += $"{key}:{minute}";
                expires   = TimeSpan.FromMinutes(5);
                break;

            case TimeType.时:
                string hour = DateTime.Now.ToString("yyyyMMddHH");
                cacheKey += $"{key}:{hour}";
                expires   = TimeSpan.FromHours(1).Add(TimeSpan.FromMinutes(5));
                break;

            case TimeType.天:
                string day = DateTime.Now.ToString("yyyyMMdd");
                cacheKey += $"{key}:{day}";
                expires   = TimeSpan.FromDays(1).Add(TimeSpan.FromMinutes(5));
                break;

            case TimeType.月:
                string month = DateTime.Now.ToString("yyyyMM");
                cacheKey += $"{key}:{month}";
                expires   = TimeSpan.FromDays(30).Add(TimeSpan.FromMinutes(5));
                break;

            default:
                break;
            }

            return(this.CheckIsOverStep(cacheKey, maxCount, expires.Value));
        }