Establishe redis connection after its lost after a few minutes
This commit is contained in:
parent
7d759f04ed
commit
34fecbf1fd
@ -17,17 +17,41 @@ namespace Worker
|
||||
try
|
||||
{
|
||||
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 = "" };
|
||||
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;
|
||||
if (json != null)
|
||||
{
|
||||
var vote = JsonConvert.DeserializeAnonymousType(json, definition);
|
||||
Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'");
|
||||
UpdateVote(pgsql, vote.voter_id, vote.vote);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
keepAliveCommand.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -66,7 +90,7 @@ namespace Worker
|
||||
|
||||
var command = connection.CreateCommand();
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS votes (
|
||||
id VARCHAR(255) NOT NULL UNIQUE,
|
||||
id VARCHAR(255) NOT NULL UNIQUE,
|
||||
vote VARCHAR(255) NOT NULL
|
||||
)";
|
||||
command.ExecuteNonQuery();
|
||||
@ -84,7 +108,7 @@ namespace Worker
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.Error.WriteLine("Connected to redis");
|
||||
Console.Error.WriteLine("Connecting to redis");
|
||||
return ConnectionMultiplexer.Connect(ipAddress);
|
||||
}
|
||||
catch (RedisConnectionException)
|
||||
@ -123,4 +147,4 @@ namespace Worker
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user