Hi @Divjot_Arora,
To achieve: Implement reconnect logic.
With several documents, I have seen two field present in the mongoDB docs for node.
I am unable to find the same variable based configuration in the mongo-go-driver 1.3.1. However as you have mentioned that it has retry mechanism present already, I am unable to implement the same.
As a alternative solution, I came up with the below.
Testing scenario:
- Connect to mongo Atlas(free tier account)
var Client *mongo.Client
func ConnectDb() bool {
duration := // some duration
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
monitor := &event.PoolMonitor{
Event: HandlePoolMonitor,
}
client, err := mongo.Connect(ctx,
options.Client().
ApplyURI(/*atlas connection uri*/).
SetMinPoolSize(/*min pool size*/).
SetMaxPoolSize(/*max pool size*/).
SetHeartbeatInterval(/* some duration*/).
SetPoolMonitor(monitor))
if err != nil {
return false
}
Client = client
return Ping()
}
func reconnect(client *mongo.Client) {
for {
if ConnectDb() {
client = Client
break
}
time.Sleep(time.Duration(configuration.AppConfig.MongoDb.ReconnectInterval) * time.Second)
}
}
func HandlePoolMonitor(evt *event.PoolEvent) {
switch evt.Type {
case event.PoolClosedEvent:
logging.AppLogger.Error("DB connection closed.")
reconnect(Client)
}
}
func main() {
ginRouter.GET("/health", func(context *gin.Context) {
Ping()
context.JSON(http.StatusOK, gin.H{
"status": "System is up and running.",
})
})
}
- Create a ping function
func Ping() bool {
if err := Client.Ping(context.TODO(), nil); err != nil {
return false
}
return true
}
- Just before the actual call to Ping method in step 2, pause the execution using debugger and call the disconnect method from client(Client.Disconnect(nil)) and continue.
Efforts made to resolve:
I tried using monitor event(PoolClosedEvent) and tried to reconnect.
Problem:
Though this code works but I believe there is a better way provided by you guys for the same considering node.js docs.
Thanks & Regards
Ankush Goyal