Go中的异步模式

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

Asynchronous patterns in go

问题

最近我在查看后端代码示例时发现,人们以同步方式执行数据库查询,例如:

result, err := db.Exec(stmt, title, content)

作为一个来自Node.js背景的人,这让我有些困扰。

我知道HTTP处理程序基本上是一个Go协程,但这样做不会阻塞整个线程直到数据库返回响应吗?

有没有异步设计模式来解决这个问题?
或者这只是Go中的一种方式?

英文:

Recently I was checking backend code examples and I see that people are executing DB queries in synchronous fashion, for example:

result, err := db.Exec(stmt, title, content)

Coming from a Nodejs background, this bothers me a bit

I understand that http handlers are pretty much a go routine, but won't this block entire thread until DB sends back a response?

Is there any asynchronous design pattern to address this problem?
Or maybe this is just a way it is in go?

答案1

得分: 3

我理解了,HTTP处理程序在Go中实际上是一个go例程,但这不会阻塞整个线程,直到数据库发送回响应。

不会。Go不是Node。在Go中没有必要像在Node中那样考虑阻塞/非阻塞,因为线程不会被“阻塞”代码阻塞。

有没有任何异步设计模式来解决这个问题?

没有,因为根本就没有问题。

或者也可以说这就是Go的方式。

英文:

> I understand that http handlers are pretty much a go routine, but won't this block entire thread until DB sends back a response?

No. Go is not Node. There is no reason to think about blocking/nonblocking in Go as threads don't get blocked by "blocking" code as in Node.

> Is there any asynchronous design pattern to address this problem?

No, because there is no problem.

> Or maybe this is just a way it is in [Go]?

Exactly.

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

发表评论

匿名网友

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

确定