GOLANG 检查 MongoDB 是否正在运行

huangapple go评论88阅读模式
英文:

GOLANG check whether mongodb is running

问题

我正在编写一个GO脚本来检查Mongo服务器是否正在运行。我的代码如下:

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())
}

但是出现错误,错误信息为"exit status 1: error: garbage option"。是否有其他方法可以使用GOLANG来检查Mongo服务器是否运行?请告诉我。

英文:

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

得分: 2

如果你想超越将一个bash脚本移植到Go语言(这往往比它值得的麻烦多),你可以使用mgo库来实际连接到一个MongoDB实例并检查其是否健康:

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服务器正常运行。")
    os.Exit(0)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2017年5月31日 19:44:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/44283880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定