<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          .NET Core中如何限制接口請求次數(shù)

          共 9946字,需瀏覽 20分鐘

           ·

          2022-08-01 05:21

          .net core中如何限制接口請求次數(shù)

          AspNetCoreRateLimit這種輪子我前面有給大家介紹過,今天就不說了,我們來聊聊背后的原理,歡迎各位大佬指正!

          像我們經(jīng)常看的一些APi請求接口網(wǎng)站:

          拿請求國外主要城市的七日接口舉例,非VIP只能使用2000次, vip用戶一天最多請求10000次,請求該接口時,必須要注冊賬號獲取到appid和密鑰。

          那我們根據(jù)這個需求,設(shè)計一個獲取天氣的限流接口。

          第一步

          校驗登錄賬號是否存在,如果不存在,我們拋出不存在的錯誤

          [HttpPost("GetWeather")]
           public IActionResult ApiLimit(WeatherInfor weatherInfor)
            {
            if (!_userService.IsValid(weatherInfor.Appid, weat   herInfor.Appsecret))
             {
              throw new Exception("賬號或者密碼錯誤");
             }
             }

          第二步

          判斷該賬戶是否是Vip用戶,如果是VIP用戶,則沒有調(diào)用總次數(shù),只有單日限制次數(shù),像這種單日限制次數(shù),隔天清空的數(shù)據(jù) 我們肯定用緩存來處理比較合理,我們設(shè)置每天的23點59分59秒所有請求緩存是否有效,這就是緩存的絕對過期時間。

          那具體業(yè)務(wù)邏輯就是這樣的 由于用戶的appid是唯一的,我們可以把它當作key值,調(diào)用的次數(shù)當作value值,如果緩存不存在我們就添加緩存,如果緩存存在 我們就獲取調(diào)用次數(shù),如果大于2000我們就告訴調(diào)用方,調(diào)用次數(shù)已用完,如果沒有 我們就從緩存中獲取調(diào)用的次數(shù),并給它+1。

          緩存類

          public class MemoryCacheHelper
              {

                  public static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

                  /// <summary>
                  /// 驗證緩存項是否存在
                  /// </summary>
                  /// <param name="key">緩存Key</param>
                  /// <returns></returns>
                  public static bool Exists(string key)
                  {
                      if (key == null)
                      {
                          return false;
                      }
                      return _cache.TryGetValue(key, out _);
                  }

                  /// <summary>
                  /// 獲取緩存
                  /// </summary>
                  /// <param name="key">緩存Key</param>
                  /// <returns></returns>
                  public static object Get(string key)
                  {
                      if (key == null)
                      {
                          throw new ArgumentNullException(nameof(key));
                      }
                      if (!Exists(key))
                          throw new ArgumentNullException(nameof(key));


                      return _cache.Get(key);
                  }

                  /// <summary>
                  /// 添加緩存
                  /// </summary>
                  /// <param name="key">緩存Key</param>
                  /// <param name="value">緩存Value</param>
                  /// <param name="expiresSliding">滑動過期時長(如果在過期時間內(nèi)有操作,則以當前時間點延長過期時間)</param>
                  /// <param name="expiressAbsoulte">絕對過期時長</param>
                  /// <returns></returns>
                  public static bool AddMemoryCache(string key, object value)
                  {
                      if (key == null)
                      {
                          throw new ArgumentNullException(nameof(key));
                      }
                      if (value == null)
                      {
                          throw new ArgumentNullException(nameof(value));
                      }
                      DateTime time = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("D").ToString()).AddSeconds(-1);
                      _cache.Set(key, value, time);
                      return Exists(key);
                  }
              }

          業(yè)務(wù)邏輯

             public bool IsLimit(string appId)
                  {
                      if (MemoryCacheHelper.Exists(appId))
                      {
                          int value = int.Parse(MemoryCacheHelper.Get(appId).ToString());
                          if (value > 2000)
                              return false;
                          else
                              value = value + 1;

                          MemoryCacheHelper.AddMemoryCache(appId, value);
                      }
                      else
                      {
                          MemoryCacheHelper.AddMemoryCache(appId, 1);
                      }
                      return true;
                  }

          最后

          去查詢天氣接口, 返回數(shù)據(jù)

             [HttpPost("GetWeather")]
                  public IActionResult ApiLimit(WeatherInfor weatherInfor)
                  {
                      if (!_userService.IsValid(weatherInfor.Appid, weatherInfor.Appsecret))
                      {
                          throw new Exception("賬號或者密碼錯誤");
                      }
                      bool isLimit = false;
                      if (_userService.IsVIP(weatherInfor.Appid))
                      {
                          isLimit= _sqlServices.IsLimit(weatherInfor.Appid);
                      }
                      else
                      {
                          isLimit = _memoryCacheServices.IsLimit(weatherInfor.Appid);
                      }
                      if (isLimit)
                      {
                          //查詢天氣接口 返回數(shù)據(jù)
                      }
                      else
                      {
                          throw new Exception("調(diào)用次數(shù)已用完");
                      }
                      return Ok("");
                  }

          最后大家如果喜歡我的文章,還麻煩給個關(guān)注并點個贊, 希望net生態(tài)圈越來越好!


          瀏覽 54
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  成人黄色片子 | 免费日韩A片 | 欧美大码一区二区免费看 | 国产成人传媒 | 成人AV一区二区三区四区 |