取消用户特定的goroutine

哈菲兹·杰弗里(Hafiz Jefri):

我有一个应用程序(网络应用程序),允许用户使用twitter oauth登录并提供自动的tweet删除功能。用户登录到Web应用程序后,我将为每个用户启动一个goroutines(通过REST api),这将删除用户tweet列表。

假设有100位用户,每个用户有500 ++条推文:

  • 如何在删除过程的中间停止删除go例程。

    例如:用户30在启动删除过程2分钟后请求停止删除推文(这应该通过对我的应用程序的API调用来完成)。

  • 考虑到http请求和twitter API限制,创建go例程以使应用程序性能最大化的最佳实践是什么?我应该为每个用户创建go例程还是实现工作者池?

信息:我正在将anaconda用于Twitter客户端后端


编辑:

我找到了一种使用带有上下文的map来实现此目的的方法。这是供参考的代码。归功于https://gist.github.com/montanaflynn/020e75c6605dbe2c726e410020a7a974

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "sync"
    "time"
)

// a concurrent safe map type by embedding sync.Mutex
type cancelMap struct {
    sync.Mutex
    internal map[string]context.CancelFunc
}

func newCancelMap() *cancelMap {
    return &cancelMap{
        internal: make(map[string]context.CancelFunc),
    }
}

func (c *cancelMap) Get(key string) (value context.CancelFunc, ok bool) {
    c.Lock()
    result, ok := c.internal[key]
    c.Unlock()
    return result, ok
}

func (c *cancelMap) Set(key string, value context.CancelFunc) {
    c.Lock()
    c.internal[key] = value
    c.Unlock()
}

func (c *cancelMap) Delete(key string) {
    c.Lock()
    delete(c.internal, key)
    c.Unlock()
}

// create global jobs map with cancel function
var jobs = newCancelMap()

// the pretend worker will be wrapped here
// https://siadat.github.io/post/context
func work(ctx context.Context, id string) {

    for {
        select {
        case <-ctx.Done():
            fmt.Printf("Cancelling job id %s\n", id)
            return
        case <-time.After(time.Second):
            fmt.Printf("Doing job id %s\n", id)
        }
    }
}

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

    // get job id and name from query parameters
    id := r.URL.Query().Get("id")

    // check if job already exists in jobs map
    if _, ok := jobs.Get(id); ok {
        fmt.Fprintf(w, "Already started job id: %s\n", id)
        return
    }

    // create new context with cancel for the job
    ctx, cancel := context.WithCancel(context.Background())

    // save it in the global map of jobs
    jobs.Set(id, cancel)

    // actually start running the job
    go work(ctx, id)

    // return 200 with message
    fmt.Fprintf(w, "Job id: %s has been started\n", id)
}

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

    // get job id and name from query parameters
    id := r.URL.Query().Get("id")

    // check for cancel func from jobs map
    cancel, found := jobs.Get(id)
    if !found {
        fmt.Fprintf(w, "Job id: %s is not running\n", id)
        return
    }

    // cancel the jobs
    cancel()

    // delete job from jobs map
    jobs.Delete(id)

    // return 200 with message
    fmt.Fprintf(w, "Job id: %s has been canceled\n", id)
}

func main() {
    http.HandleFunc("/start", startHandler)
    http.HandleFunc("/stop", stopHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
icza:

您无法从外部停止goroutine,goroutine必须支持取消操作。有关详细信息,请参阅:在Go中取消阻止操作支持取消的常见方法是渠道和context套餐。

至于哪个对您更好,那太广泛了。这取决于很多事情,但是对于示例/参考,标准库的HTTP服务器在其自己的goroutine中为每个传入的HTTP请求提供服务,并具有不错的性能。

如果您的请求率很高,则可能值得创建和使用goroutine池(或使用执行此操作的第三方库/路由器),但这实际上取决于您的实际代码,您应该对应用进行评估/配置,以确定是否它是必需的还是值得的。

通常,我们可以说,如果与创建/计划goroutine所需的开销相比,每个goroutine所做的工作都“繁重”,通常只使用一个新的goroutine更为干净。与启动goroutine相比,在goroutine中访问第三方服务(例如Twitter API)可能会比在启动goroutine时有更多数量级的工作和更多延迟,因此您应该为每个功能启动goroutine(而不会影响性能)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章