简体   繁体   English

PM2 NodeJS集群 - 我应该考虑在使用pm2时进行同步

[英]PM2 NodeJS cluster - Should I consider synchronizing when using pm2

My express server does a very simple work - saving the request url into a file (via fs.appendFile). 我的快速服务器做了一个非常简单的工作 - 将请求URL保存到文件中(通过fs.appendFile)。

I suppose it works fine when not using pm2, because it has only one process, so no other process/thread saving the same file at the same time. 我想它在不使用pm2时工作正常,因为它只有一个进程,所以没有其他进程/线程同时保存同一个文件。

But when using pm2, I don't know if it will occur two processes write the same file at the same time? 但是当使用pm2时,我不知道是否会发生两个进程同时写入同一个文件? Thanks. 谢谢。

When you use pm2 on cluster mode, request routing will happen using Round Robin algorithm. cluster模式下使用pm2时,将使用Round Robin算法进行请求路由。 That means the cluster master accepts all the incoming connections and routes them to the child processes (one request to one child process). 这意味着集群master接受所有传入连接并将它们路由到子进程(对一个子进程的一个请求)。

So, one request will be routed to one child process and the same request won't be processed by another process. 因此,一个请求将被路由到一个子进程,并且同一请求将不会被另一个进程处理。

For your above case, When you receive two different requests from two different clients then they will be processed by two different processes. 对于上述情况,当您收到来自两个不同客户端的两个不同请求时,它们将由两个不同的进程处理。

As long as you have a logic to create a unique file name even though the requests handled at the same time, you won't get any issues. 只要你有一个逻辑来创建一个唯一的文件名,即使请求同时处理,你也不会遇到任何问题。

You will get issues only if you try to write the files by two different processes with the same file name. 只有当您尝试使用具有相同文件名的两个不同进程编写文件时,才会出现问题。

If you write different files from different clients with different file names then it won't be an issue. 如果您使用不同的文件名从不同的客户端编写不同的文件,那么这将不是问题。

Note : As a request from one client will be processed by one process, two or more processes won't process the same request and won't write the same file twice. 注意 :由于来自一个客户端的请求将由一个进程处理,因此两个或多个进程将不处理相同的请求,并且不会将同一文件写入两次。

The issue will occur, If you write different files from different clients with the same file name. 如果您使用相同的文件名从不同的客户端编写不同的文件,则会出现此问题。

Hope you understand :-) 希望你能理解 :-)

Yes it may mess when multiple processes writing/appending the same file at the same time. 是的,当多个进程同时写入/附加同一文件时,它可能会混乱。 So then best way is to only use one process to write file, or you have to synchronize them 那么最好的方法是只使用一个进程来写文件,或者你必须同步它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM