@@ -17,17 +17,41 @@ public static int Main(string[] args)
17
17
try
18
18
{
19
19
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" ;
21
27
22
28
var definition = new { vote = "" , voter_id = "" } ;
23
29
while ( true )
24
30
{
31
+ // Reconnect redis if down
32
+ if ( redisConn == null || ! redisConn . IsConnected ) {
33
+ Console . WriteLine ( "Reconnecting Redis" ) ;
34
+ redis = OpenRedisConnection ( "redis" ) . GetDatabase ( ) ;
35
+ }
25
36
string json = redis . ListLeftPopAsync ( "votes" ) . Result ;
26
37
if ( json != null )
27
38
{
28
39
var vote = JsonConvert . DeserializeAnonymousType ( json , definition ) ;
29
40
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 ( ) ;
31
55
}
32
56
}
33
57
}
@@ -66,7 +90,7 @@ private static NpgsqlConnection OpenDbConnection(string connectionString)
66
90
67
91
var command = connection . CreateCommand ( ) ;
68
92
command . CommandText = @"CREATE TABLE IF NOT EXISTS votes (
69
- id VARCHAR(255) NOT NULL UNIQUE,
93
+ id VARCHAR(255) NOT NULL UNIQUE,
70
94
vote VARCHAR(255) NOT NULL
71
95
)" ;
72
96
command . ExecuteNonQuery ( ) ;
@@ -84,7 +108,7 @@ private static ConnectionMultiplexer OpenRedisConnection(string hostname)
84
108
{
85
109
try
86
110
{
87
- Console . Error . WriteLine ( "Connected to redis" ) ;
111
+ Console . Error . WriteLine ( "Connecting to redis" ) ;
88
112
return ConnectionMultiplexer . Connect ( ipAddress ) ;
89
113
}
90
114
catch ( RedisConnectionException )
@@ -123,4 +147,4 @@ private static void UpdateVote(NpgsqlConnection connection, string voterId, stri
123
147
}
124
148
}
125
149
}
126
- }
150
+ }
0 commit comments