如何用WebSockets、Nodejs实现PM2集群

How to implement PM2 clustering with WebSockets, Nodejs

我正在使用 Node js(Express) 中的 WebSocket(ws) 库编写实时连接 Web 服务器。所以当我 运行 服务器处于 pm2 集群模式时,websocket 无法正常工作 properly.Is使用 websocket 在 pm2 集群之间共享数据的任何方式。

您可以将库切换到socket.io they already solve this issue by using redis adapter for socket.io Socket.IO Redis

By running socket.io with the socket.io-redis adapter you can run multiple socket.io instances in different processes or servers that can all broadcast and emit events to and from each other.

据我了解,这就是集群模式的意义所在。它无法在多个 "nodes" 运行 进程中保持连接。直接来自 PM2 文档:

确保您的应用程序是无状态的,这意味着没有本地数据存储在进程中,例如 sessions/websocket 连接、会话内存和相关数据。使用 Redis、Mongo 或其他数据库在进程之间共享状态。

如果您可以将您的 websocket 拉到它自己的实例中并避免 pm2 集群的副作用——这可能是性能最高的,尽管在您的设置中可能不可行。祝你好运!