每个用户处理一条消息



我有一个红色列表,我将其用作队列。我把元素推到左边,然后从右边弹出。来自不同用户的请求被推送到队列中。我有一个goroutine池,可以从队列(POP(中读取请求并处理它们。我希望一次只能处理每个用户 ID 的一个请求。我有一个永远运行的 ReadRequest(( 函数,它 POP 一个具有 userID 的请求。我需要按照每个用户进来的顺序处理每个用户的请求。我不确定如何实现这一点。我是否需要每个用户 ID 的 redis 列表?如果是这样,我将如何遍历处理其中请求的所有列表?

for i:=0; i< 5; i++{
wg.Add(1)
go ReadRequest(&wg)
}

func ReadRequest(){
for{
//redis pop request off list
request:=MyRedisPop()
fmt.Println(request.UserId)
// only call Process if no other goroutine is processing a request for this user
Process(request)

time.sleep(100000)
}
wg.Done()
}

以下是无需创建多个 Redis 列表即可使用的伪代码:

// maintain a global map for all users
// if you see a new user, call NewPerUser() and add it to the list
// Then, send the request to the corresponding channel for processing
var userMap map[string]PerUser 
type PerUser struct {
chan<- redis.Request // Whatever is the request type
semaphore *semaphore.Weighted // Semaphore to limit concurrent processing
}
func NewPerUser() *PerUser {
ch := make(chan redis.Request)
s := semaphore.NewWeighted(1) // One 1 concurrent request is allowed
go func(){
for req := range ch {
s.Acquire(context.Background(), 1)
defer s.Release(1)
// Process the request here
}
}()
}

请注意,这只是一个伪代码,我还没有测试它是否有效。

相关内容

最新更新