tsedio / tsed

:triangular_ruler: Ts.ED is a Node.js and TypeScript framework on top of Express to write your application with TypeScript (or ES6). It provides a lot of decorators and guideline to make your code more readable and less error-prone. ⭐️ Star to support our work!
https://tsed.io/
MIT License
2.86k stars 284 forks source link

[Socket.io] How to using socket.io with pm2 cluster mode #2438

Open sonpham-bmd opened 1 year ago

sonpham-bmd commented 1 year ago

Is your feature request related to a problem? Please describe.

I'm using socket.io with pm2 cluster mode (4 instances), when the socket init on multiple nodes, it's can not merge all socket in one. I read docs https://socket.io/docs/v4/pm2/, but it's use http module. Please help me check this case. Thank you so much! 🙏

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

Acceptance criteria

No response

Romakita commented 1 year ago

Hello @sonpham-bmd

You can try this solution:

import {Server as IOServer, ServerOptions} from "socket.io";
import { createAdapter } from "@socket.io/cluster-adapter";
import { setupWorker } from "@socket.io/sticky";

@Configuration()
class Server {
  @IO()
  private io: IOServer;

  $afterSocketListen() {
     this.io.adapter(createAdapter());

     setupWorker(this.io);
  } 
}

See you

Romakita commented 1 year ago

Note: Github discussion is more appropriate for this topic

sonpham-bmd commented 1 year ago

Hello @sonpham-bmd

You can try this solution:

import {Server as IOServer, ServerOptions} from "socket.io";
import { createAdapter } from "@socket.io/cluster-adapter";
import { setupWorker } from "@socket.io/sticky";

@Configuration()
class Server {
  @IO()
  private io: IOServer;

  $afterSocketListen() {
     this.io.adapter(createAdapter());

     setupWorker(this.io);
  } 
}

See you

Screenshot 2023-09-20 at 14 37 27

after add, server can not start.

Romakita commented 1 year ago

ok I don't know why. did you start the process with pm2 ?

sonpham-bmd commented 1 year ago

ok I don't know why. did you start the process with pm2 ?

I run pm2 with ecosystem file js module.exports = { apps: [ { name: '248-backend', exec_mode: 'cluster', instances: 2, script: './dist/src/index.js', args: 'start', watch: true } ] }

Romakita commented 1 year ago

@sonpham-bmd Ok can you create small repo example please.