前面有一件事:如果您正在運行HTTP服務器(無論如何都是Go的標準服務器),則無法停止並重新啓動服務器就無法控制goroutine的數量。每個請求至少啓動一個goroutine,並且你無能爲力。好消息是,這通常不是問題,因爲goroutine非常輕巧。然而,你想保持正在努力工作的goroutines的數量是完全合理的。
您可以將任何值放入通道中,包括函數。因此,如果目標是隻需要在http處理程序中編寫代碼,那麼應該關閉這些工作 - 工作人員不知道(或關心)他們正在處理的是什麼。
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
var largePool chan func()
var smallPool chan func()
func main() {
// Start two different sized worker pools (e.g., for different workloads).
// Cancelation and graceful shutdown omited for brevity.
largePool = make(chan func(), 100)
smallPool = make(chan func(), 10)
for i := 0; i < 100; i++ {
go func() {
for f := range largePool {
f()
}
}()
}
for i := 0; i < 10; i++ {
go func() {
for f := range smallPool {
f()
}
}()
}
http.HandleFunc("/endpoint-1", handler1)
http.HandleFunc("/endpoint-2", handler2) // naming things is hard, okay?
http.ListenAndServe(":8080", nil)
}
func handler1(w http.ResponseWriter, r *http.Request) {
// Imagine a JSON body containing a URL that we are expected to fetch.
// Light work that doesn't consume many of *our* resources and can be done
// in bulk, so we put in in the large pool.
var job struct{ URL string }
if err := json.NewDecoder(r.Body).Decode(&job); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
go func() {
largePool <- func() {
http.Get(job.URL)
// Do something with the response
}
}()
w.WriteHeader(http.StatusAccepted)
}
func handler2(w http.ResponseWriter, r *http.Request) {
// The request body is an image that we want to do some fancy processing
// on. That's hard work; we don't want to do too many of them at once, so
// so we put those jobs in the small pool.
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
go func() {
smallPool <- func() {
processImage(b)
}
}()
w.WriteHeader(http.StatusAccepted)
}
func processImage(b []byte) {}
這是一個非常簡單的例子來說明問題。設置工作池的方式並不重要。你只需要一個聰明的工作定義。在上面的例子中它是一個閉包,但是你也可以定義一個Job接口。現在
type Job interface {
Do()
}
var largePool chan Job
var smallPool chan Job
,我不會把整個工作池方法 「簡單」。你說你的目標是限制goroutines(正在工作)的數量。這根本不需要工人;它只需要一個限制器。這和上面的例子是一樣的,但是使用通道作爲信號來限制併發。
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
var largePool chan struct{}
var smallPool chan struct{}
func main() {
largePool = make(chan struct{}, 100)
smallPool = make(chan struct{}, 10)
http.HandleFunc("/endpoint-1", handler1)
http.HandleFunc("/endpoint-2", handler2)
http.ListenAndServe(":8080", nil)
}
func handler1(w http.ResponseWriter, r *http.Request) {
var job struct{ URL string }
if err := json.NewDecoder(r.Body).Decode(&job); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
go func() {
// Block until there are fewer than cap(largePool) light-work
// goroutines running.
largePool <- struct{}{}
defer func() { <-largePool }() // Let everyone that we are done
http.Get(job.URL)
}()
w.WriteHeader(http.StatusAccepted)
}
func handler2(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
go func() {
// Block until there are fewer than cap(smallPool) hard-work
// goroutines running.
smallPool <- struct{}{}
defer func() { <-smallPool }() // Let everyone that we are done
processImage(b)
}()
w.WriteHeader(http.StatusAccepted)
}
func processImage(b []byte) {}
Go的http包爲每個傳入連接啓動一個go例程。除非你在談論後臺工作處理,否則這似乎是浪費精力。 – squiguy
是的,這是爲了後臺處理。有些人可能需要一段時間才能完成,我寧願不讓一個不受控制的goroutines寬鬆 –
goroutines有什麼問題?它們基本上是內置異步支持的jobqueue實現。 –