一段基於Redis-SortedSet的限流程式碼

丶Pz發表於2018-09-05
  [HttpGet]
        public async Task<ActionResult<string>> Get()
        {
            //限流週期:5秒
            int period = 5;
            //週期內請求數限制:5次,即限制每五秒只能請求五次
            int maxCount = 5;
            long uid = 123456;
            string action = "login";
            string key = string.Format("hist:{0}{1}", uid, action);
            long current = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            var batch = db.CreateBatch();
            var tasks = new List<Task>();
            //加入SortedSet
            tasks.Add(batch.SortedSetAddAsync(key, current, current));
            //移除五秒之前的記錄
            tasks.Add(batch.SortedSetRemoveRangeByScoreAsync(key, 0, current - period * 1000));
            //重置過期時間
            tasks.Add(batch.KeyExpireAsync(key, TimeSpan.FromSeconds(period + 1)));
            batch.Execute();

            //獲取請求的次數
            long currentCount = await db.SortedSetLengthAsync(key);
            //返回是否大於限制次數
            bool res = currentCount <= maxCount;

            return res ? "未被限流,正常請求" : "超過請求頻次,限制請求";
        }

相關文章