Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created January 18, 2021 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielplawgo/660da8eefe402a4eea8e6e500f81208f to your computer and use it in GitHub Desktop.
Save danielplawgo/660da8eefe402a4eea8e6e500f81208f to your computer and use it in GitHub Desktop.
RateLimiter limitowanie ilości żądań
static async Task ConsoleExample()
{
var timeConstraint = TimeLimiter.GetFromMaxCountByInterval(5, TimeSpan.FromSeconds(1));
for (int i = 0; i < 100; i++)
{
await timeConstraint;
Console.WriteLine($"{DateTime.Now:MM/dd/yyy HH:mm:ss.fff}");
}
}
static async Task FlurlClientExample()
{
var url = "https://visualstudio.plawgo.pl";
var cli = new FlurlClient(url).Configure(settings => {
settings.HttpClientFactory = new HttpClientFactory();
});
for (int i = 0; i < 20; i++)
{
var content = await cli.Request().GetStringAsync();
Console.WriteLine($"Page downloaded: {content.Length}");
}
}
static async Task FlurlGlobalExample()
{
FlurlHttp.Configure(settings => {
settings.HttpClientFactory = new HttpClientFactory();
});
var url = "https://visualstudio.plawgo.pl";
for (int i = 0; i < 20; i++)
{
var content = await url.GetStringAsync();
Console.WriteLine($"Page downloaded: {content.Length}");
}
}
static async Task HttpClientExample()
{
var handler = TimeLimiter
.GetFromMaxCountByInterval(5, TimeSpan.FromSeconds(10))
.AsDelegatingHandler();
var client = new HttpClient(handler);
for (int i = 0; i < 20; i++)
{
var content = await client.GetStringAsync("https://visualstudio.plawgo.pl");
Console.WriteLine($"Page downloaded: {content.Length}");
}
}
public class HttpClientFactory : DefaultHttpClientFactory
{
public override HttpMessageHandler CreateMessageHandler()
{
var handler = TimeLimiter
.GetFromMaxCountByInterval(5, TimeSpan.FromSeconds(10))
.AsDelegatingHandler();
handler.InnerHandler = base.CreateMessageHandler();
return handler;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment