duanmeng9336 2017-04-11 20:35
浏览 44

golang如何延迟工作?

I'm trying to handle reconnections to MongoDB. To do this I try to perform every operation three times (in case it fails with io.EOF)

type MongoDB struct {
    session *mgo.Session
    DB      *mgo.Database
}

func (d MongoDB) performWithReconnect(collection string, 
operation func(*mgo.Collection) error) error {
    var err error
    for i := 0; i < 3; i++ {
        session := d.session.Copy()
        defer session.Close()
        err = operation(session.DB(Config.MongoDb).C(collection))
        if err == io.EOF{
            continue
        }
        if err == nil{
            return err
        }
    }
    return err
}

So the question is about defer. Will it close all sessions as I suppose or it is going to behave some other way? If you know some good practices to handle this different way I will be happy to read them.

  • 写回答

2条回答 默认 最新

  • dougekui1518 2017-04-11 21:01
    关注

    From A Tour of Go:

    A defer statement defers the execution of a function until the surrounding function returns.

    So in your code, you're creating three (identical) defer functions, which will all run when the function exits.

    If you need a defer to run inside of a loop, you have to put it inside of a function. This can be done in an anonymous function thusly:

    for i := 0; i < 3; i++ {
        err := func() error {
            session := d.session.Copy()
            defer session.Close()
            return operation(session.DB(Config.MongoDb).C(collection))
        }()
        if err == io.EOF {
            continue
        }
        if err != nil {
            return err
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗