using System;
using System.Collections.Generic;
using System.Threading;

namespace Common
{
    public class RateLimiter
    {
        private static readonly object lockObject = new object();
        private static readonly int requestsPerSecond = 5;//每秒允许请求5次
        private static int remainingRequests;//剩余请求次数
        private static long lastRequestTime;//上次请求时间
        /// <summary>
        /// 实现速率限制。它根据指定的每秒请求数量来控制请求是否被允许
        /// </summary>
        static RateLimiter()
        {
            remainingRequests = requestsPerSecond;
            lastRequestTime = DateTime.UtcNow.Ticks;
        }
        /// <summary>
        /// 实现速率限制：默认每秒允许请求5次
        /// </summary>
        /// <returns></returns>
        public static bool TryRequest()
        {
            lock (lockObject)
            {
                long currentTime = DateTime.UtcNow.Ticks;//当前请求时间
                long elapsedTicks = currentTime - lastRequestTime;
                double elapsedSeconds = elapsedTicks / TimeSpan.TicksPerSecond;

                remainingRequests += (int)(elapsedSeconds * requestsPerSecond);

                if (remainingRequests > requestsPerSecond)
                {
                    remainingRequests = requestsPerSecond;
                }

                if (remainingRequests > 0)
                {
                    remainingRequests--;
                    lastRequestTime = currentTime;
                    return true;
                }

                return false;
            }
        }
    }
}
