所有独立的任务是否应该在HTTP请求的goroutine之外进行处理?

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

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.

huangapple
  • 本文由 发表于 2015年4月18日 01:05:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/29705412.html
匿名

发表评论

匿名网友

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

确定