douyou1960 2017-05-31 11:44
浏览 99
已采纳

GOLANG检查mongodb是否正在运行

I am writing a GO script to check whether Mongo server is running. My code is as,

import "bytes"
import "os/exec"
import "fmt"

func main() {
    cmd := exec.Command("ps", "-ef", "|", "grep", "mongod", "|", "grep", "-v", "grep", "|", "wc", "-l", "|", "tr", "-d", "'", "'")

    fmt.Println(cmd)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Result: " + out.String())
}

But Getting Error as , "exit status 1: error: garbage option" . Is there other way to check this with GOLANG? Please let me know.

  • 写回答

1条回答 默认 最新

  • doulangxun7769 2017-05-31 13:29
    关注

    If you want to go beyond porting a bash script to Go (which is often more trouble than it's worth), you can use the mgo library to actually connect to a MongoDB instance and check if it is healthy:

    package main
    
    import (
        "gopkg.in/mgo.v2"
        "fmt"
        "os"
    )
    
    func main() {
        sess, err := mgo.Dial("localhost")
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        defer sess.Close()
        err = sess.Ping()
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        fmt.Println("MongoDB server is healthy.")
        os.Exit(0)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大