我是新来的.假设我有一台服务器在监听HTTP请求,同时我需要判断Redis通知以便更新数据.下面是一个示例:

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

server.ListenAndServe()

在Goroutine中简单地放入checkExpire是一个好的解决方案吗?

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.


And never use Empty loop (for{}) see:
Difference between the main goroutine and spawned goroutines of a Go program

空循环使用this%的CPU内核,根据您可能使用的用例等待某些操作:
-sync.WaitGroup喜欢this
-select {}this
-渠道
-time.Sleep

Go相关问答推荐

进入缓冲通道同步

如何使用Docker Compose配置Go,使main. go文件位于/CMD文件夹中

带有条件的for循环中缺少RETURN语句

错误&对象已被Golang在K8s操作符上修改

exec的可执行决议.命令+路径

无法使用exec从管道中读取.Go中的命令

如何使用 go 读取 RDF xml 文件中的 XML 命名空间属性

从带有嵌套括号的字符串中提取值

该文件位于模块.内,该模块不包含在您的工作区中

在VSCode中如何使用特定的文件名提供编译命令

如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf struct ?

Github Actions Go lambda 项目不同的 sha256sums

如何过滤来自 fsnotify 的重复系统消息

如何编写一个以字符串或错误为参数的通用函数?

Golang Getrlimit 返回与 ulimit 不同的值

自定义指标未显示在 prometheus web ui 中,grafana 中也是如此

将 Simple Go Web 应用程序部署到 Elastic Beanstalk

GOENV 只能使用 OS 环境设置

传递上下文的最佳方式

在 Go 中,为什么 exec.Command() 失败但 os.StartProcess() 成功启动winget.exe?