Establishe redis connection after its lost after a few minutes

This commit is contained in:
Manuel Belsak 2016-11-30 13:59:21 +00:00
parent 7d759f04ed
commit 34fecbf1fd

View File

@ -17,19 +17,43 @@ namespace Worker
try try
{ {
var pgsql = OpenDbConnection("Server=db;Username=postgres;"); var pgsql = OpenDbConnection("Server=db;Username=postgres;");
var redis = OpenRedisConnection("redis").GetDatabase(); var redisConn = OpenRedisConnection("redis");
var redis = redisConn.GetDatabase();
// Keep alive is not implemented in Npgsql yet. This workaround was recommended:
// https://github.com/npgsql/npgsql/issues/1214#issuecomment-235828359
var keepAliveCommand = pgsql.CreateCommand();
keepAliveCommand.CommandText = "SELECT 1";
var definition = new { vote = "", voter_id = "" }; var definition = new { vote = "", voter_id = "" };
while (true) while (true)
{ {
// Reconnect redis if down
if (redisConn == null || !redisConn.IsConnected) {
Console.WriteLine("Reconnecting Redis");
redis = OpenRedisConnection("redis").GetDatabase();
}
string json = redis.ListLeftPopAsync("votes").Result; string json = redis.ListLeftPopAsync("votes").Result;
if (json != null) if (json != null)
{ {
var vote = JsonConvert.DeserializeAnonymousType(json, definition); var vote = JsonConvert.DeserializeAnonymousType(json, definition);
Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'"); Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'");
// Reconnect DB if down
if (!pgsql.State.Equals(System.Data.ConnectionState.Open))
{
Console.WriteLine("Reconnecting DB");
pgsql = OpenDbConnection("Server=db;Username=postgres;");
}
else
{ // Normal +1 vote requested
UpdateVote(pgsql, vote.voter_id, vote.vote); UpdateVote(pgsql, vote.voter_id, vote.vote);
} }
} }
else
{
keepAliveCommand.ExecuteNonQuery();
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -84,7 +108,7 @@ namespace Worker
{ {
try try
{ {
Console.Error.WriteLine("Connected to redis"); Console.Error.WriteLine("Connecting to redis");
return ConnectionMultiplexer.Connect(ipAddress); return ConnectionMultiplexer.Connect(ipAddress);
} }
catch (RedisConnectionException) catch (RedisConnectionException)