Jeffail/tunny goroutine 池工具

goroutine 池工具已经有好多了,好多都会基于channel或者cas 进行开发设计
谷歌的errgroup以及machine 都是一个不错的选择,Jeffail/tunny 也是一个比较稳定
的包

参考使用

  • main.go
 
 package main
import (
    "io/ioutil"
    "net/http"
    "runtime"
    "github.com/Jeffail/tunny"
)
func main() {
    numCPUs := runtime.NumCPU()
    pool := tunny.NewFunc(numCPUs, func(payload interface{}) interface{} {
        return payload
    })
    defer pool.Close()
    http.HandleFunc("/work", func(w http.ResponseWriter, r *http.Request) {
        input, err := ioutil.ReadAll(r.Body)
        if err != nil {
            http.Error(w, "Internal error", http.StatusInternalServerError)
        }
        defer r.Body.Close()
        // Funnel this work into our pool. This call is synchronous and will
        // block until the job is completed.
        result := pool.Process(input)
        w.Write(result.([]byte))
    })
    http.ListenAndServe(":8080", nil)
}

说明

tunny同时还支持其他的特性,比如超时,也支持进行状态的处理,同时machine 是一个很不错的选择,支持的特性也比较多

参考资料

https://pkg.go.dev/golang.org/x/sync/errgroup
https://github.com/autom8ter/machine
https://github.com/Jeffail/tunny

posted on 2020-12-29 18:01  荣锋亮  阅读(438)  评论(0编辑  收藏  举报

导航