英文:
golang: web service that monitors worker goroutine
问题
假设我正在使用golang编写一个REST Web服务。在内部,我有几个工作goroutine来执行任务。这些goroutine是通过HTTP API按需触发的。当然,我希望能够以某种方式监控这些goroutine的进度。通常,会有一个通道供goroutine发送更新、错误等信息,而主程序会在这些通道上使用select
语句。
然而,由于主程序的事件循环忙于http.ListenAndServe()
,我无法找到一种实现这一目标的方法。鉴于这似乎是一个相当常见的问题,我想知道是否有我所不知道的设计模式。
[编辑]
更多技术细节。我有一个Resource
类来管理资源池。Resource.DoSomething()
是一个耗时操作,因此它会在后台启动一个goroutine。会打开一个通道来允许轮询状态。
当某个特定的HTTP请求到达时,会触发DoSomething()
。但我没有上下文来轮询状态。目前,我愚蠢的计划是在下一个HTTP请求到达时轮询通道以获取输入。这应该是足够的,但并不理想——我希望能立即了解goroutine中正在发生的情况。
英文:
Suppose I'm writing a REST web service in golang. Internally I have several worker goroutine that does things. Such goroutine are triggered on demand by the HTTP API. Of course I'd like to monitor the progress of these goroutines somehow. Normally there will be a channel for the goroutine to send updates, error, etc. And the main program would do select
on those channels.
However, because the even loop of the main program is busy with http.ListenAndServe()
, I can't see a way to achieve this. Given that this seems like a quite common issue to have, I'm wondering if there is a design pattern that I'm missing.
[EDIT]
Some more technical detail. So I have a Resource
class that manages a pool of resources. Resource.DoSomething()
is a long operation, so it'll kick of a goroutine in the back ground. A channel will be opened to allow status to be polled.
When a certain HTTP request comes in, this DoSomething()
gets triggered. But I have no context to poll the status from. Currently my silly plan is to poll the channel for input when the next HTTP request comes in. This should be sufficient but not ideal - I'd like to know what's going on in that goroutine right away.
答案1
得分: 3
启动一个Go协程来专门运行包含监视的select语句,并将select语句放在它自己的for
循环中:
func main() {
go func() {
for {
select {
//TODO: 在这里插入代码?
}
}
}()
err := http.ListenAndServe()
if err != nil {
//TODO:
}
}
英文:
Launch a Go routine to specifically run the select that contains the monitoring, putting the select in it's own for
loop:
func main() {
go func() {
for {
select {
//TODO: Insert Code Here?
}
}
}()
err := http.ListenAndServe()
if err != nil {
//TODO:
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论