2 回答

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

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);
}
}
}
}
}
- 2 回答
- 0 關注
- 246 瀏覽
添加回答
舉報