du8864 2017-01-12 16:35
浏览 150
已采纳

Golang:即使数据库关闭,Ping也会第二次成功

I have run into an interesting issue, namely, that db.Ping() does not return an error even if the database has been killed since the first attempt.

Source code below:

import (
    "database/sql"
    "fmt"
    "log"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

type database struct {
    datasource string
    conn       *sql.DB
}

// Connect creates and initialises a Database struct
func (db *database) Connect(server, user, password, DBPort string) error {
    var err error

    db.datasource = fmt.Sprintf("%s:%s@/", user, password)
    db.conn, err = sql.Open(server, db.datasource)
    if err != nil {
        log.Fatal(err)
    }

    err = db.conn.Ping()
    if err != nil {
        db.conn.Close()
        return err
    }

    log.Println("Waiting for 15 seconds, kill the DB")
    <-time.After(15 * time.Second)

    err = db.conn.Ping()
    if err != nil {
        db.conn.Close()
        return err
    }

    log.Println("Second ping successful")

    return nil
}

At first, the database is up, so the first Ping succeeds. However, I put a delay in there just for the sake of testing. In that 15 seconds I stop the database (sudo service mysql stop), however, db.Ping() still succeeds.

If I were to execute any actual query (via db.Query, db.QueryRow or db.Exec), then the sql package would panic with Broken Pipe (which is expected).

Am I doing something wrong?

also: go version go1.7.1 linux/amd64

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • douhuilin1152 2017-01-12 17:15
    关注

    Ping, after the first connection, doesn't actually ping the database. It's odd, and wrong, but that's the way it works (until Go 1.8). If there's an existing connection in the connection pool that hasn't timed out, Ping will simply remove it from the pool and return it to you, without actually bothering to check if the database is still there.

    Kardianos (who wrote the above linked document, as well as Govendor) fixed this in 1.8, provided the database driver supports it. Until then, however, Ping isn't reliable for determining if the database is still there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染