英文:
Should all independent tasks be processed outside the http request goroutine?
问题
由于golang在单独的goroutine中处理传入的请求,我不清楚哪些类型的任务应该延迟处理,例如通过消息队列(如NSQ消费者)处理,哪些应该在http请求的goroutine中处理。
英文:
Since golang handles incoming requests in separate goroutines, it's unclear to me which types of tasks should be deferred for processing by a message queue e.g. NSQ consumers and which should be handled within the http request goroutine.
答案1
得分: 2
由于net/http
包会运行每个请求,所以你不需要担心阻塞请求的goroutine。你真正需要问自己的问题是:“在返回响应给客户端之前,我需要在这之前做这个吗?还是可以推迟到以后再做?”通常,如果我需要从数据库获取数据来提供响应,那么会阻塞请求的goroutine,这是可以接受的。如果我现在可以返回响应,并在队列中放置一条消息以便以后处理,那也是可以的。
由于请求的goroutine几乎没有成本,并且与其他请求隔离,所以你真的不需要太担心它。做对客户端有意义的事情即可。
英文:
Since the net/http
package runs each request you do not need to worry about blocking the request goroutine. The real question you should ask myself is "Do I need to do this before I return a response to the client, or can it be deferred until later". Generally if I need to fetch from a database to serve a response that will block the request goroutine, and that is ok. If I can return a response now and put a message on a queue to do stuff later, that can be ok too.
Since the request goroutine has little cost to exist, and it is isolated from other requests, you really don't need to worry about it that much. Do what makes sense for the client.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论