使用express处理多个请求
我有 Java 背景,而且对 Node 还比较陌生。我试图理解节点与它是单线程的事实,但仍然可以同时处理多个请求。 我已经阅读了有关单线程和事件循环的内容,以及相关的 stackoverflow 问题,但我仍然不确定我是否正确理解它,因此提出了这个问题。
我有一个简单的 http 服务,它接受 id 作为输入。可以有多个请求几乎同时使用相同的id,当然也可以几乎同时有其他请求使用其他id。
当调用服务时,会发生以下情况:
- 在 DB 中查找 id(以阻塞方式,即等待)
- 如果 DB 查找没有找到结果,则将 id 插入 DB
假设几乎同时有两个请求,相同的 ID。 我的问题是以下是否可能:
- 请求 1 在数据库中进行查找 ->无结果
- 请求 2 在数据库中进行查找 ->无结果
- 请求 1 插入新行
- 请求 2 插入新行
查找的阻塞方式让我猜测答案是“不,那是不可能的”,但后来我读到阻塞不会阻塞单个线程。是什么让我想回答“是的,这是可能的”,是因为我不明白如果上述不可能的话,如何处理多个请求。
谢谢, -路易丝
I have a background with Java and I am relatively new to node. I am trying to understand node in relation to the fact that it is single threaded, but can still handle multiple requests at the same time.
I have read about the single thread and the event loop, as well as the related stackoverflow questions, but I am still not sure I have understood it correctly, hence this question.
I have a simple http service that takes an id as an input. There can be multiple requests at almost the same time with the same id, and of course also other requests at almost the same time with other ids.
When the service is called, the following happens:
- Lookup id in DB (in a blocking manner, i.e. await)
- If the DB lookup did not find a result, insert id in DB
Let's say there are two requests at almost the same time, with the same id.
My question is whether the following is possible:
- Request 1 makes the lookup in the DB -> no result
- Request 2 makes the lookup in the DB -> no result
- Request 1 inserts a new row
- Request 2 insert a new row
The blocking manner of the lookup makes me guess the answer is "no, that is not possible", but then I read that the blocking does not block the single thread. What makes me want to answer "yes, it is possible", is because I do not understand how several requests can be handled, if the above is not possible.
Thanks,
-Louise
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,答案是“是的,这是可能的”。对数据库调用的“await”确保在我们继续下一行代码之前查询已完成,但它不会阻塞线程。
该线程在等待数据库操作完成时继续执行其他任务,并且这些其他任务可能正在处理另一个请求。这意味着多个请求之间可能会发生竞争条件。
As far as I can determine the answer is "yes, that is possible". The "await" on the call to the DB ensures that the query has finished before we continue to the next line of code, but it does not block the thread.
The thread continues with other tasks while awaiting the DB operation to finish, and those other tasks might be handling another request. This means that a race condition can happen between multiple requests.