Golang:监控工作协程的 Web 服务

huangapple go评论90阅读模式
英文:

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:
    }
}

huangapple
  • 本文由 发表于 2014年9月18日 17:33:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/25909065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定