在Golang中运行后台任务和服务器监听的最佳实践是什么?

时间:2016-10-06 17:43:54

标签: go goroutine

我是Go的新手。假设我有一个服务器正在侦听HTTP请求,同时我需要检查Redis通知,以便我可以更新数据。以下是一个例子:

func checkExpire() {
    for {
        switch msg := pubSubConn.Receive().(type) {
        case redis.Message:
        ...
    }
}

server.ListenAndServe()

简单地将checkExpire放入goroutine是一个很好的解决方案吗?

go func() {
    for {
        switch msg := pubSubConn.Receive().(type) {
        case redis.Message:
        ...
    }
}()

1 个答案:

答案 0 :(得分:10)

是的,请记住warning: unsequenced modification and access to 'i' [-Wunsequenced] 也是goroutine,这是工作代码:

undef.c: In function ‘main’:
undef.c:7:24: warning: operation on ‘i’ may be undefined [-Wsequence-point]
             s1[i] = s1[++i];
                        ^~~

运行代码并打开browser

永远不要使用空循环(main)看:
Difference between the main goroutine and spawned goroutines of a Go program

空循环使用100%的CPU核心,根据您可能使用的用例等待某些操作:
  - package main import ( "fmt" "net/http" "time" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func checkExpire() { for { // do some job fmt.Println(time.Now().UTC()) time.Sleep(1000 * time.Millisecond) } } func main() { go checkExpire() http.HandleFunc("/", handler) // http://127.0.0.1:8080/Go http.ListenAndServe(":8080", nil) } ,如this   - for{},如this   - 频道
  - sync.WaitGroup