运行 后台任务和服务器侦听的最佳做法是什么
What's the best practices to run a background task along with server listening
我是 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:
...
}
}()
是的,记住 main
也是一个 goroutine,这里是工作代码:
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)
}
运行 代码并打开您的 browser.
永远不要使用空循环(for{}
)见:
Difference between the main goroutine and spawned goroutines of a Go program
空循环使用 100% 的 CPU 核心,根据您可能使用的用例等待一些操作:
- sync.WaitGroup
喜欢 this
- select {}
喜欢 this
- 频道
- time.Sleep
我是 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:
...
}
}()
是的,记住 main
也是一个 goroutine,这里是工作代码:
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)
}
运行 代码并打开您的 browser.
永远不要使用空循环(for{}
)见:
Difference between the main goroutine and spawned goroutines of a Go program
空循环使用 100% 的 CPU 核心,根据您可能使用的用例等待一些操作:
- sync.WaitGroup
喜欢 this
- select {}
喜欢 this
- 频道
- time.Sleep