我是Go的新手.假设我有一台服务器正在侦听HTTP请求,同时我需要检查Redis通知,以便我可以更新数据.以下是一个例子:
func checkExpire() {
for {
switch msg := pubSubConn.Receive().(type) {
case redis.Message:
...
}
}
server.ListenAndServe()
Run Code Online (Sandbox Code Playgroud)
简单地将checkExpiregoroutine 放入一个好的解决方案吗?
go func() {
for {
switch msg := pubSubConn.Receive().(type) {
case redis.Message:
...
}
}()
Run Code Online (Sandbox Code Playgroud)
小智 13
是的,请记住这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)
}
Run Code Online (Sandbox Code Playgroud)
运行代码并打开浏览器.
永远不要使用Empty loop(for{})参见:
Go程序的主goroutine和衍生goroutines之间的差异
空循环使用100%的CPU核心,根据您可能使用的用例等待某些操作:
- sync.WaitGroup像这样
- select {}像这样
- 频道
-time.Sleep