Skip to content

Instantly share code, notes, and snippets.

@explorer14

explorer14/WithRetryPolicy.cs Secret

Last active Jan 19, 2020
Embed
What would you like to do?
private static string ConnectionString =
"Server=db.com;Port=3306;Database=MyDB;Uid=user;Ssl Mode=Required;Pwd=bla;Pooling=True;ConnectionLifeTime=60";
private static void WriteResiliently()
{
var policies = Policy
.Handle<MySqlException>(x => x.IsFailoverException())
.WaitAndRetry(5,
retry => TimeSpan.FromSeconds(retry * 5),
(a, b) =>
{
var mySqlEx = a as MySqlException;
Log.Logger.Warning(
"Failed with: {@error}. Retrying in {x} seconds...",
new
{
Msg = mySqlEx.Message,
Number = mySqlEx.Number,
HR = mySqlEx.HResult
},
b.TotalSeconds);
});
for (var i = 0; i < 10_000; i++)
{
policies.Execute(() =>
{
try
{
using (var conn = new MySqlConnection(ConnectionString))
{
conn.Open();
conn.Insert(new Record { Id = i + 1, Name = $"Aman {i + 1}" });
Log.Logger.Information(
"Inserted row with id {id} successfully!",
i + 1);
}
}
catch (MySqlException mysqlEx)
{
if (mysqlEx.IsFailoverException())
{
Log.Logger.Warning(
"Clearing current connection pool because an exception {@exception} occurred",
new
{
Msg = mysqlEx.Message,
Number = mysqlEx.Number,
HR = mysqlEx.HResult
});
// for this call to do anything, the idle pool should have non-zero connections
// which it will after the connection is disposed. This increases the likelihood
// of retries succeeding.
MySqlConnection.ClearPool(conn);
}
throw mysqlEx;
}
});
Thread.Sleep(100);
}
}
public static class MySqlExceptionExtensions
{
public static bool IsFailoverException(this MySqlException mySqlException)
{
return mySqlException.Number == (int)MySqlErrorCode.UnableToConnectToHost ||
mySqlException.Number == (int)MySqlErrorCode.OptionPreventsStatement ||
(mySqlException.Number == 0 && mySqlException.HResult == -2147467259);
// Fatal error reading from the stream, usually Number being 0 means host connection issues
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.