亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C#中的油門方法

C#中的油門方法

C#
Helenr 2021-12-05 14:56:58
我有向某些 3rd 方 API 發出請求并從中返回響應的方法。由于此 API 每 1 分鐘僅允許 50 次調用,因此我想限制對此 API 的請求。目前我正在考慮使用 Polly 并在我的代碼中添加諸如包裝器之類的東西var policy = Policy.Handle<HttpRequestException>()                   .WaitAndRetryForever(retryAttempt => TimeSpan.FromMinutes(1));var response = await policy.ExecuteAsync(async () => await DoApiCallAsync()                           .ConfigureAwait(false));return response;但也許這里有更好的方法來做到這一點。
查看完整描述

2 回答

?
holdtom

TA貢獻1805條經驗 獲得超10個贊

Polly很好,我們在我們的基礎設施中使用它在我們的微服務之間進行重試機制,但是我不推薦.WaitAndRetryForever,因為它聽起來真的很危險,就像@Stefan 說的那樣。如果第 3 方 API 在 30 分鐘內進行維護/停機/無響應會發生什么我知道它不會經常發生,但仍然發生。

我會建議使用Polly來克服網絡問題。例如,第 3 方 API 可能的網絡停機時間,但與節流無關。

關于節流,我建議創建一些基于隊列的模式,您可以在其中存儲請求并以給定的速率處理它們。

可悲的是,這還有兩個缺點:

  1. 您將需要在您的一端實現一些邏輯,以便此隊列不會變得非常大并使您的進程消耗大量內存。

  2. 如果有人等待超過一定時間才能收到他們的回復,這可能是糟糕的用戶體驗。

由于我不知道您的 API 的性質,因此就我所能提供的建議而言,您必須決定這是否適合您。祝你好運!

注意: .waitAndRetryForever如果您將其用于內部通信并且想要放松服務級別協議,那還不錯。(例如,您不希望您的整個基礎架構僅僅因為一項服務死亡而崩潰)。


查看完整回答
反對 回復 2021-12-05
?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

我更喜歡控制一切(根據需要自定義)


您還可以擴展工作人員以并行發出多個請求


例子


Worker worker = new Worker();

worker.OnRetry += (id) =>

{

  //called when error occurs

  //here you can wait as you want and send next request

};

worker.OnRespnse += (sender, success) =>

{

  //called on response

  //customize success depend on response status-code/body

  //here you can wait as you want and send next request

};

worker.Start("request body");

//you can start this worker over and over

工人階級


using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

using System.Threading.Tasks;


namespace app

{

    class Worker

    {


        public delegate void OnRetryDelegate(int id);


        public event OnRetryDelegate OnRetry;


        public delegate void OnRespnseDelegate(Worker sender, bool success);


        public event OnRespnseDelegate OnRespnse;


        public Worker()

        {

            Id = IdProvider.GetNewId();

            thread = new Thread(new ThreadStart(ExecuteAsync));

            thread.Start();

        }


        private readonly Thread thread;

        public string Number;

        public bool Idle { get; set; }

        public bool ShutDown { get; set; }

        public bool Started { get; set; }

        public int Id { get; private set; }

        public PostData { get; set; }


        public void Start(string postData)

        {

            PostData = postData;

            Idle = true;

            Started = true;

        }


        private void ExecuteAsync()

        {

            while (!ShutDown)

            {

                Thread.Sleep(1500);

                if (Idle)

                {

                    Idle = false;

                    if (Number == "terminate")

                    {

                        ShutDown = true;

                        return;

                    }


                    try

                    {

                        var request = (HttpWebRequest) WebRequest.Create("https://example.com");

                        var data = Encoding.ASCII.GetBytes(postData);

                        Debug.Print("send:  " + postData);

                        request.Method = "POST";

                        request.ContentType = "application/x-www-form-urlencoded";

                        request.ContentLength = data.Length;

                        using (var stream = request.GetRequestStream())

                        {

                            stream.Write(data, 0, data.Length);

                        }

                        var response = (HttpWebResponse) request.GetResponse();

                        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                        Debug.Print(responseString);

                        if (responseString.Contains("something"))

                            OnRespnse?.Invoke(this, true);

                    }

                    catch (Exception)

                    {

                        OnRetry?.Invoke(Id);

                    }


                    OnRespnse?.Invoke(this, false);

                }

            }

        }

    }

}



查看完整回答
反對 回復 2021-12-05
  • 2 回答
  • 0 關注
  • 246 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號