dongqing904999 2016-06-08 07:32
浏览 37
已采纳

Golang HTTP服务器实现

I have read that net/http starts a go subroutine for each connection. I have few questions. But I haven't seen any parameter to limit the number of spawned new go subroutines. For example, If I have to handle 1 million concurrent requests per second, what will happen? Do we have any control over spawned go subroutines? If it spawns one go subroutine per connection, won't it choke my entire system? What is the recommended way of handling huge number of concurrent requests for a go webserver? I have to handle both cases of responses being asynchronous and synchronous.

  • 写回答

1条回答 默认 最新

  • dongzipu7517 2016-06-08 07:46
    关注

    Job/Worker pattern is a well common go concurrency pattern suited for this task.

    Multiple goroutines can read from a single channel, distributing an amount of work between CPU cores, hence the workers name. In Go, this pattern is easy to implement - just start a number of goroutines with channel as parameter, and just send values to that channel - distributing and multiplexing will be done by Go runtime.

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func worker(tasksCh <-chan int, wg *sync.WaitGroup) {
        defer wg.Done()
        for {
            task, ok := <-tasksCh
            if !ok {
                return
            }
            d := time.Duration(task) * time.Millisecond
            time.Sleep(d)
            fmt.Println("processing task", task)
        }
    }
    
    func pool(wg *sync.WaitGroup, workers, tasks int) {
        tasksCh := make(chan int)
    
        for i := 0; i < workers; i++ {
            go worker(tasksCh, wg)
        }
    
        for i := 0; i < tasks; i++ {
            tasksCh <- i
        }
    
        close(tasksCh)
    }
    
    func main() {
        var wg sync.WaitGroup
        wg.Add(36)
        go pool(&wg, 36, 50)
        wg.Wait()
    }
    

    All goroutines run in parallel, waiting for channel to give them work. The goroutines receive their work almost immediately one after another.

    Here is a great article about how you can handle 1 million requests per minute in go: http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?