【发布时间】:2020-09-26 01:49:00
【问题描述】:
我每秒通过通道收到大约 200 000 条消息到我的工作人员,我需要将发送给客户端的消息数量限制为每秒 20 条。 这使它每 50 毫秒 1 条消息
在 LOOP 的帮助下,worker 将在整个程序生命周期内仍然活着(而不是为每条消息打开一个通道)。
我的目标: - 由于消息的顺序很重要,我想跳过在阻塞的 50 毫秒内收到的所有消息,只保存最新的消息 - 如果最新的消息在阻塞的 50 毫秒内出现,我希望在循环内的阻塞时间结束并且没有新消息到来时处理保存的消息!
我的策略 - 不断向同一频道发送尚未处理的最新消息
但它的问题是,如果该消息是在(来自应用程序的)新消息之后发送的呢?
下面的代码更像是一个作为工作代码的算法,只是想要一个关于如何做的提示/方法。
func example (new_message_from_channel <-chan *message) {
default = message
time = now_milliseconds
diff_accepted = 50milli
for this_message := range new_message_from_channel {
if now_millisecond - time >= diff_accepted {
send_it_to_the_client
time = now_milliseconds
} else {
//save the latest message
default = this_message
//My problem is how to process this latest message when the blocked 50ms is over and no new message coming ?!
//My strategy - keep sending it to the same channel
theChannel <- default
}
}
}
如果你有优雅的方法,欢迎与我分享:)
【问题讨论】:
-
使用速率限制器,例如godoc.org/golang.org/x/time/rate
-
@colm.anseo 我看不出如何整合它,你能给我举个例子吗?谢谢!
-
刚刚发布了
golang.org/x/time/rate的用法示例