猿问

如何限制Go API的并发连接

我正在使用 Listenandserve 启动 Go API 来接受 HTTP 请求。

我怎样才能实现以下目标?

  1. 允许最多 100 个并发 HTTP 请求

  2. 第 101 个请求(以及任何其他请求)应等待 10 分钟,以尝试落入“100 个同时”限制(即希望前 100 个请求中的一些请求应该完成)

  3. 如果 10 分钟过去了并且没有打开可用的请求“槽”,则为一直在等待的请求返回错误

  4. 接下来运行请求 101...102...x 的顺序并不重要

当前版本完全不可用:


    timeout := time.After(10 * time.Minute)

    tick := time.Tick(15 * time.Second)

    fullcmdfirst := fmt.Sprintf("netstat -anp | grep procname | grep ESTABLISHED | grep -v grep | wc -l")

    outputfirst, err1first := exec.Command("/bin/sh", "-c", fullcmdfirst).CombinedOutput()

    if strconv.ParseFloat(string(outputfirst)) < 100 {

        return nil

    }


    // Keep trying until we're timed out or lock acquired

    for {

        select {

        // Got a timeout! fail with a timeout error

        case <-timeout:

            return errors.New("Error: timed out ")

        // Got a tick, we should check if we can acquire

        case <-tick:

            fullcmd := fmt.Sprintf("netstat -anp | grep procname | grep ESTABLISHED | grep -v grep | wc -l")

            output, err1 := exec.Command("/bin/sh", "-c", fullcmd).CombinedOutput()

            if strconv.ParseFloat(string(outputfirst)) < 100 {

                l.Printf("start req")

                return nil

            }

        }

    }


扬帆大鱼
浏览 121回答 1
1回答

HUH函数

不需要 netstats 或代码或任何其他东西(无论如何它都不起作用 - 一旦 netstat 看到 <100 个连接,就没有什么可以阻止接下来的 100 个请求,而你最终会一次运行 199 个请求;加上,等待处理的请求仍然会出现在 netstat 中 - 限制连接完全是一个不同的问题)。只需使用缓冲通道作为信号量即可;它已经是线程安全的了。sem := make(chan struct{}, 100)func myHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; timeout := time.After(10 * time.Minute)&nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <- timeout:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, "Sorry", http.StatusUnavailable)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; case sem <- struct{}:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; w.Write([]byte("Hello"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <- sem&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }}但请注意,大多数客户端在 10 分钟之前就已经超时了。
随时随地看视频慕课网APP

相关分类

Go
我要回答