| | |
| | | using System.Linq; |
| | | using System.Text; |
| | | using System.Threading.Tasks; |
| | | using System.Timers; |
| | | using Timer = System.Timers.Timer; |
| | | |
| | | namespace WIDESEA_Common; |
| | | |
| | | public class HttpsClient |
| | | { |
| | | private static readonly Timer cleanupTimer; |
| | | |
| | | static HttpsClient() |
| | | { |
| | | // 设置定时器,每5分钟清理一次requestTracker的数据 |
| | | cleanupTimer = new Timer(2 * 60 * 1000); |
| | | cleanupTimer.Elapsed += CleanupRequestTracker; |
| | | cleanupTimer.AutoReset = true; |
| | | cleanupTimer.Enabled = true; |
| | | } |
| | | |
| | | private static readonly LogFactory LogFactory = new LogFactory(); |
| | | |
| | | // 封装一个用HttpClient发送GET请求的方法有参数 |
| | |
| | | |
| | | // 用于追踪每个请求的调用次数和最后请求时间。 |
| | | private static readonly Dictionary<string, (int Count, DateTime LastRequestTime)> requestTracker = new(); |
| | | |
| | | // 封装一个用HttpClient发送Post请求的方法有参数 |
| | | public static async Task<string> PostAsync(string url, Dictionary<string, object> parameters) |
| | | { |
| | | // 创建一个新的字典,排除 RequestTime 和 SessionId |
| | | var filteredParameters = parameters.Where(p => p.Key != "RequestTime"&& p.Key != "SessionId").ToDictionary(p => p.Key, p => p.Value); |
| | | var filteredParameters = parameters.Where(p => p.Key != "RequestTime" && p.Key != "SessionId").ToDictionary(p => p.Key, p => p.Value); |
| | | |
| | | string requestKey = $"{url}:{JsonConvert.SerializeObject(filteredParameters)}"; |
| | | // 检查请求次数和时间限制 |
| | | // 检查请求次数和时间限制 |
| | | if (requestTracker.TryGetValue(requestKey, out var requestInfo)) |
| | | { |
| | | if (requestInfo.Count >= 5 && DateTime.Now < requestInfo.LastRequestTime.AddMinutes(3)) |
| | | if (requestInfo.Count >= 10 && DateTime.Now < requestInfo.LastRequestTime.AddMinutes(2)) |
| | | { |
| | | // 如果请求次数超过限制且未超过10分钟,抛出异常 |
| | | Console.WriteLine("请求次数已达到限制,请稍后再试。"); |
| | | Console.WriteLine($"接口地址:{url}"); |
| | | Console.WriteLine($"请求数据:{JsonConvert.SerializeObject(filteredParameters, Formatting.Indented)}"); |
| | | throw new Exception($"接口地址:{url}---请求次数已达到限制,请稍后再试。"); |
| | | throw new Exception($"接口地址:{url}---请求次数已达到限制,请稍后再试。"); |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | // 清理requestTracker的方法 |
| | | private static void CleanupRequestTracker(object sender, ElapsedEventArgs e) |
| | | { |
| | | // 获取当前时间 |
| | | DateTime now = DateTime.Now; |
| | | |
| | | // 遍历并清理requestTracker中超过10分钟的记录 |
| | | var keysToRemove = requestTracker.Keys.Where(key => now > requestTracker[key].LastRequestTime.AddMinutes(2)).ToList(); |
| | | |
| | | foreach (var key in keysToRemove) |
| | | { |
| | | requestTracker.Remove(key); |
| | | } |
| | | } |
| | | } |