为了账号安全,请及时绑定邮箱和手机立即绑定

如何限制Go API的并发连接

如何限制Go API的并发连接

Go
扬帆大鱼 2023-07-26 13:27:37
我正在使用 Listenandserve 启动 Go API 来接受 HTTP 请求。我怎样才能实现以下目标?允许最多 100 个并发 HTTP 请求第 101 个请求(以及任何其他请求)应等待 10 分钟,以尝试落入“100 个同时”限制(即希望前 100 个请求中的一些请求应该完成)如果 10 分钟过去了并且没有打开可用的请求“槽”,则为一直在等待的请求返回错误接下来运行请求 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            }        }    }
查看完整描述

1 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

不需要 netstats 或代码或任何其他东西(无论如何它都不起作用 - 一旦 netstat 看到 <100 个连接,就没有什么可以阻止接下来的 100 个请求,而你最终会一次运行 199 个请求;加上,等待处理的请求仍然会出现在 netstat 中 - 限制连接完全是一个不同的问题)。只需使用缓冲通道作为信号量即可;它已经是线程安全的了。


sem := make(chan struct{}, 100)


func myHandler(w http.ResponseWriter, r *http.Request) {

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

    select {

        case <- timeout:

            http.Error(w, "Sorry", http.StatusUnavailable)

            return

        case sem <- struct{}:

            w.Write([]byte("Hello"))

            <- sem

            return

    }

}

但请注意,大多数客户端在 10 分钟之前就已经超时了。


查看完整回答
反对 回复 2023-07-26
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信