首頁 > 後端開發 > Golang > 主體

如何使用 MGO 從 Go 中的 MongoDB 連線故障中優雅地恢復?

Mary-Kate Olsen
發布: 2024-11-14 14:53:02
原創
704 人瀏覽過

How to Gracefully Recover from MongoDB Connection Failures in Go with MGO?

Recovering from MongoDB Connection Failure in Go with MGO

In Go, the MGO package is used to interact with MongoDB. However, connecting to MongoDB can sometimes fail, causing a panic in the program. This article provides a solution to gracefully recover from such connection failures.

The following function attempts to connect to MongoDB and return a session and collection if successful:

func connectToMongo(sess *mgo.Session, coll *mgo.Collection, sessionErr error) bool {
    fmt.Println("enter main - connecting to mongo")

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Detected panic")
            var ok bool
            err, ok := r.(error)
            if !ok {
                fmt.Printf("pkg:  %v,  error: %s", r, err)
            }
        }
    }()

    maxWait := time.Duration(5 * time.Second)
    session, sessionErr = mgo.DialWithTimeout("localhost:27017", maxWait)
    if sessionErr == nil {
        session.SetMode(mgo.Monotonic, true)
        coll = session.DB("MyDB").C("MyCollection")
        if coll != nil {
            fmt.Println("Got a collection object")
            return true
        }
    } else { // never gets here
        fmt.Println("Unable to connect to local mongo instance!")
    }
    return false
}
登入後複製

The problem with the original code is that the panic interrupt the program before the defer function can execute. To fix this, the recover() function should be called inside the defer statement, after the connection attempt.

The modified code:

var mongoUp bool

func init() {
    if ( connectToMongo() ) {
        mongoUp := true
        fmt.Println("Connected")
    } else {
        mongoUp = false
        fmt.Println("Not Connected")
    }
}
登入後複製

When MongoDB is running, the program successfully connects and sets mongoUp to true. When MongoDB is not running, the program logs the failure and sets mongoUp to false.

This solution allows the program to gracefully handle MongoDB connection failures and continue execution without crashing.

以上是如何使用 MGO 從 Go 中的 MongoDB 連線故障中優雅地恢復?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板