Skip to content

Commit badedbf

Browse files
committed
Use exit signal handler to terminate the process cleanly
Signed-off-by: Md Soharab Ansari <[email protected]>
1 parent 1735cb6 commit badedbf

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

Diff for: redis-http-connector/main.go

+14-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"log"
77
"net/http"
88
"os"
9+
"os/signal"
10+
"syscall"
911

1012
"github.com/go-redis/redis/v8"
1113
"go.uber.org/zap"
@@ -19,7 +21,7 @@ type redisConnector struct {
1921
logger *zap.Logger
2022
}
2123

22-
func (conn redisConnector) consumeMessage(ctx context.Context) {
24+
func (conn redisConnector) consumeMessage(sigterm chan os.Signal) {
2325

2426
headers := http.Header{
2527
"KEDA-Topic": {conn.connectordata.Topic},
@@ -29,14 +31,16 @@ func (conn redisConnector) consumeMessage(ctx context.Context) {
2931
"KEDA-Source-Name": {conn.connectordata.SourceName},
3032
}
3133

34+
var ctx = context.Background()
3235
forever := make(chan bool)
3336

3437
go func() {
3538
for {
3639
// BLPop will block and wait for a new message if the list is empty
3740
msg, err := conn.rdbConnection.BLPop(ctx, 0, conn.connectordata.Topic).Result()
3841
if err != nil {
39-
conn.logger.Fatal("Error in consuming queue: ", zap.Error((err)))
42+
conn.logger.Error("Error in consuming queue: ", zap.Error((err)))
43+
forever <- false
4044
}
4145

4246
if len(msg) > 1 {
@@ -57,13 +61,15 @@ func (conn redisConnector) consumeMessage(ctx context.Context) {
5761
err = response.Body.Close()
5862
if err != nil {
5963
conn.logger.Error(err.Error())
64+
forever <- false
6065
}
6166
}
6267
}
6368
}
6469
}()
6570
conn.logger.Info("Redis consumer up and running!")
6671
<-forever
72+
sigterm <- syscall.SIGTERM
6773
}
6874

6975
func (conn redisConnector) errorHandler(ctx context.Context, err error) {
@@ -118,16 +124,20 @@ func main() {
118124
}
119125
password := os.Getenv("PASSWORD_FROM_ENV")
120126

121-
var ctx = context.Background()
122127
rdb := redis.NewClient(&redis.Options{
123128
Addr: address,
124129
Password: password,
125130
})
126131

132+
sigterm := make(chan os.Signal, 1)
127133
conn := redisConnector{
128134
rdbConnection: rdb,
129135
connectordata: connectordata,
130136
logger: logger,
131137
}
132-
conn.consumeMessage(ctx)
138+
conn.consumeMessage(sigterm)
139+
140+
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM)
141+
<-sigterm
142+
logger.Info("Terminating: Redis consumer")
133143
}

0 commit comments

Comments
 (0)