@@ -20,13 +20,16 @@ import (
20
20
log "github.com/sirupsen/logrus"
21
21
)
22
22
23
- var mongoClient * mongo.Client
24
- var mongoClientCtx context.Context
25
- var mongoClientCtxCancel context.CancelFunc
23
+ var (
24
+ mongoClient * mongo.Client
25
+ mongoClientCtx context.Context
26
+ mongoClientCtxCancel context.CancelFunc
27
+ connectionString string
28
+ )
26
29
27
30
func InitMongoClient (mongoDb string ) {
28
31
var err error
29
- connectionString : = "mongodb://" + mongoDb + "/?keepAlive=true"
32
+ connectionString = "mongodb://" + mongoDb + "/?keepAlive=true"
30
33
31
34
// Set up a context for the connection.
32
35
mongoClientCtx , mongoClientCtxCancel = context .WithCancel (context .Background ())
@@ -66,20 +69,54 @@ func CloseMongoConn() {
66
69
func checkDBConnection () {
67
70
errorCounter := 0
68
71
for {
69
- if errorCounter < 10 {
70
- time .Sleep (1 * time .Second )
71
- err := mongoClient .Ping (mongoClientCtx , nil )
72
- if err != nil {
73
- fmt .Println ("FAILED PINGING MONGO" )
74
- errorCounter ++
75
- continue
72
+ time .Sleep (1 * time .Second )
73
+ err := mongoClient .Ping (mongoClientCtx , nil )
74
+
75
+ if err != nil {
76
+ errorCounter ++
77
+ log .WithFields (log.Fields {
78
+ "error_count" : errorCounter ,
79
+ "error" : err ,
80
+ }).Warn ("Failed to ping MongoDB" )
81
+
82
+ if err := reconnectMongo (); err != nil {
83
+ log .WithFields (log.Fields {
84
+ "error_count" : errorCounter ,
85
+ "error" : err ,
86
+ }).Error ("Failed to reconnect to MongoDB" )
87
+
88
+ if errorCounter >= 30 {
89
+ log .Fatal ("Lost connection to MongoDB server and failed to reconnect after 30 attempts!" )
90
+ }
91
+ } else {
92
+ log .Info ("MongoDB connection restored" )
93
+ errorCounter = 0
76
94
}
77
- } else {
78
- log .Fatal ("Lost connection to MongoDB server for more than 10 seconds!" )
79
95
}
80
96
}
81
97
}
82
98
99
+ func reconnectMongo () error {
100
+ if mongoClient != nil {
101
+ if err := mongoClient .Disconnect (mongoClientCtx ); err != nil {
102
+ log .WithError (err ).Error ("Failed to disconnect from MongoDB" )
103
+ }
104
+ }
105
+
106
+ clientOptions := options .Client ().ApplyURI (connectionString )
107
+ newClient , err := mongo .Connect (mongoClientCtx , clientOptions )
108
+ if err != nil {
109
+ return fmt .Errorf ("failed to reconnect to MongoDB: %v" , err )
110
+ }
111
+
112
+ if err := newClient .Ping (mongoClientCtx , nil ); err != nil {
113
+ return fmt .Errorf ("failed to ping new MongoDB connection: %v" , err )
114
+ }
115
+
116
+ mongoClient = newClient
117
+ return nil
118
+ }
119
+
83
120
func GetProviderFromDB (nickname string ) (models.Provider , error ) {
84
121
var provider models.Provider
85
122
coll := mongoClient .Database ("gads" ).Collection ("providers" )
0 commit comments