一段基于Redis-SortedSet的限流代码

  [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 ? "未被限流,正常请求" : "超过请求频次,限制请求";
        }
posted @ 2018-09-05 21:37  丶Pz  阅读(321)  评论(0编辑  收藏  举报