【发布时间】:2019-01-13 05:04:49
【问题描述】:
我有一个应用程序(网络应用程序)让用户使用 twitter oauth 登录并提供自动推文删除功能。在用户登录到网络应用程序后,我将为每个用户启动一个 goroutines(通过 REST api),这将删除用户推文列表。
假设会有 100 个用户,每个用户有 500++ 条推文:
-
如何在删除过程中停止删除 go 例程。
例如:用户 30 在启动删除过程 2 分钟后请求停止删除推文(这应该通过对我的应用程序的 API 调用来完成)。
- 考虑到 http 请求和 twitter API 限制,创建 go 例程以最大限度地提高应用程序性能的最佳实践是什么。我应该为每个用户创建 go 例程还是实现工作池?
信息:我将anaconda 用于 twitter 客户端后端
编辑:
我找到了一种使用带有上下文的地图来实现这一点的方法。这是供参考的代码。归功于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))
}
【问题讨论】:
-
为了在中间停止 goroutines 使用 channel 发送一个信号来停止 goroutine。
-
你有没有尝试过?如果可以,能否贴出相关代码?
-
用代码编辑过的帖子
标签: go twitter concurrency goroutine