Skip to content

Commit 34fecbf

Browse files
committed
Establishe redis connection after its lost after a few minutes
1 parent 7d759f0 commit 34fecbf

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

worker/src/Worker/Program.cs

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,41 @@ public static int Main(string[] args)
1717
try
1818
{
1919
var pgsql = OpenDbConnection("Server=db;Username=postgres;");
20-
var redis = OpenRedisConnection("redis").GetDatabase();
20+
var redisConn = OpenRedisConnection("redis");
21+
var redis = redisConn.GetDatabase();
22+
23+
// Keep alive is not implemented in Npgsql yet. This workaround was recommended:
24+
// https://github.com/npgsql/npgsql/issues/1214#issuecomment-235828359
25+
var keepAliveCommand = pgsql.CreateCommand();
26+
keepAliveCommand.CommandText = "SELECT 1";
2127

2228
var definition = new { vote = "", voter_id = "" };
2329
while (true)
2430
{
31+
// Reconnect redis if down
32+
if (redisConn == null || !redisConn.IsConnected) {
33+
Console.WriteLine("Reconnecting Redis");
34+
redis = OpenRedisConnection("redis").GetDatabase();
35+
}
2536
string json = redis.ListLeftPopAsync("votes").Result;
2637
if (json != null)
2738
{
2839
var vote = JsonConvert.DeserializeAnonymousType(json, definition);
2940
Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'");
30-
UpdateVote(pgsql, vote.voter_id, vote.vote);
41+
// Reconnect DB if down
42+
if (!pgsql.State.Equals(System.Data.ConnectionState.Open))
43+
{
44+
Console.WriteLine("Reconnecting DB");
45+
pgsql = OpenDbConnection("Server=db;Username=postgres;");
46+
}
47+
else
48+
{ // Normal +1 vote requested
49+
UpdateVote(pgsql, vote.voter_id, vote.vote);
50+
}
51+
}
52+
else
53+
{
54+
keepAliveCommand.ExecuteNonQuery();
3155
}
3256
}
3357
}
@@ -66,7 +90,7 @@ private static NpgsqlConnection OpenDbConnection(string connectionString)
6690

6791
var command = connection.CreateCommand();
6892
command.CommandText = @"CREATE TABLE IF NOT EXISTS votes (
69-
id VARCHAR(255) NOT NULL UNIQUE,
93+
id VARCHAR(255) NOT NULL UNIQUE,
7094
vote VARCHAR(255) NOT NULL
7195
)";
7296
command.ExecuteNonQuery();
@@ -84,7 +108,7 @@ private static ConnectionMultiplexer OpenRedisConnection(string hostname)
84108
{
85109
try
86110
{
87-
Console.Error.WriteLine("Connected to redis");
111+
Console.Error.WriteLine("Connecting to redis");
88112
return ConnectionMultiplexer.Connect(ipAddress);
89113
}
90114
catch (RedisConnectionException)
@@ -123,4 +147,4 @@ private static void UpdateVote(NpgsqlConnection connection, string voterId, stri
123147
}
124148
}
125149
}
126-
}
150+
}

0 commit comments

Comments
 (0)