Skip to content

Commit

Permalink
added timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
ignatandrei committed Oct 8, 2023
1 parent 136d9f4 commit a1e6446
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 1 deletion.
47 changes: 47 additions & 0 deletions 2023/Polly/code/PollyDemo/ConsoleTest/Emp.Weather.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

using Polly.Timeout;
using System.Collections;

namespace ConsoleTest;

internal class EmpWeather
{
static string url = $"http://localhost:5223/api";
static HttpClient httpClient = new HttpClient();
static string lastWeather = "this is cold from cache";
public static async Task GetWeather(params int[] empId)
{
foreach (var it in empId)
{

var urlLimit = $"{url}/Employee/GetWeatherForEmp/{it}";
var timeoutPolicy =
Policy.TimeoutAsync(
TimeSpan.FromSeconds(value: 10),
TimeoutStrategy.Pessimistic,
async (context, timespan, task) =>
{

WriteLine("timeout ");


});

var dataPolicy = await timeoutPolicy
.ExecuteAndCaptureAsync(async () =>
{
return await httpClient.GetStringAsync(urlLimit);
});

if (dataPolicy.Outcome == OutcomeType.Successful)
{
WriteLine($"real weather for {it} is " + dataPolicy.Result);
}
else
{
WriteLine($"cache weather for {it} is " + lastWeather);
}

}
}
}
6 changes: 5 additions & 1 deletion 2023/Polly/code/PollyDemo/ConsoleTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
#endregion
#region RateLimiting
//await EmployeeRateLimiting.CalculateHistoryOld(4, 234, 579, 3423, 8756, 45, 2);
await EmployeeRateLimiting.CalculateHistoryPolly(4, 234, 579, 3423, 8756, 45, 2);
//await EmployeeRateLimiting.CalculateHistoryPolly(4, 234, 579, 3423, 8756, 45, 2);

#endregion
#region Timeout
await EmpWeather.GetWeather(4, 234, 579, 3423, 8756, 45, 2);

#endregion
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ public async Task<string> GetHistoryNOW_LimitedConcurrency(int empId)
return "this is the history for " + empId;
}

[HttpGet("{empId}")]
public async Task<string> GetWeatherForEmp(int empId)
{
Console.WriteLine("trying to get weather for " + empId);
await Task.Delay(Random.Shared.Next(empId) * 100);
Console.WriteLine("found weather for " + empId);
return "I found that is very cold ";
}

}
}

0 comments on commit a1e6446

Please # to comment.