登录
首页 >  Golang >  Go问答

每个用户处理一条消息

来源:stackoverflow

时间:2024-03-31 12:54:24 159浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《每个用户处理一条消息》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我在 redis 中有一个列表,我将其用作队列。我将元素推入左侧并从右侧弹出。来自不同用户的请求被推入队列。我有一个 goroutine 池,它从队列(pop)中读取请求并处理它们。我希望每个用户 id 一次只能处理一个请求。我有一个永远运行的 readrequest() 函数,它会弹出一个具有 userid 的请求。我需要按用户进来的顺序处理每个用户的请求。我不知道如何实现这一点。我需要每个 userid 的 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
        }
    }()
}

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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《每个用户处理一条消息》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>