2 回答

TA貢獻(xiàn)1805條經(jīng)驗 獲得超10個贊
Polly
很好,我們在我們的基礎(chǔ)設(shè)施中使用它在我們的微服務(wù)之間進(jìn)行重試機(jī)制,但是我不推薦.WaitAndRetryForever
,因為它聽起來真的很危險,就像@Stefan 說的那樣。如果第 3 方 API 在 30 分鐘內(nèi)進(jìn)行維護(hù)/停機(jī)/無響應(yīng)會發(fā)生什么我知道它不會經(jīng)常發(fā)生,但仍然發(fā)生。
我會建議使用Polly
來克服網(wǎng)絡(luò)問題。例如,第 3 方 API 可能的網(wǎng)絡(luò)停機(jī)時間,但與節(jié)流無關(guān)。
關(guān)于節(jié)流,我建議創(chuàng)建一些基于隊列的模式,您可以在其中存儲請求并以給定的速率處理它們。
可悲的是,這還有兩個缺點(diǎn):
您將需要在您的一端實現(xiàn)一些邏輯,以便此隊列不會變得非常大并使您的進(jìn)程消耗大量內(nèi)存。
如果有人等待超過一定時間才能收到他們的回復(fù),這可能是糟糕的用戶體驗。
由于我不知道您的 API 的性質(zhì),因此就我所能提供的建議而言,您必須決定這是否適合您。祝你好運(yùn)!
注意: .waitAndRetryForever
如果您將其用于內(nèi)部通信并且想要放松服務(wù)級別協(xié)議,那還不錯。(例如,您不希望您的整個基礎(chǔ)架構(gòu)僅僅因為一項服務(wù)死亡而崩潰)。

TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
我更喜歡控制一切(根據(jù)需要自定義)
您還可以擴(kuò)展工作人員以并行發(fā)出多個請求
例子
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);
}
}
}
}
}
- 2 回答
- 0 關(guān)注
- 247 瀏覽
添加回答
舉報