douyingp82418 2016-10-06 17:43
浏览 162
已采纳

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

I'm new to Go. Say I have a server listening to HTTP request, and at the same time I need to check Redis notification so I can update data. Below is an example:

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

server.ListenAndServe()

Does simply putting checkExpire into a goroutine a good solution?

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

1条回答 默认 最新

  • doutao1171 2016-10-07 15:12
    关注

    Yes, and remember that main is a goroutine too, here is the working code:

    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 the code and open your browser.


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

    Empty loop uses 100% of a CPU Core, to wait for some operation depending to the use case you may use:
    - sync.WaitGroup like this
    - select {} like this
    - channels
    - time.Sleep

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。