Integrating WebSocketGateway with Microservices in NestJS
Integrating WebSocketGateway with Microservices in NestJS
Motivation
Using WebsocketGateway as a gateway: after receiving the client’s long-lived connection, forward the message to the microservice through the RabbitMQ message queue for further processing. After the microservice finishes processing, it also sends the result to RabbitMQ; when WebsocketGateway receives the message, it sends it back to the client.
Directory structure
|
|
Files
First, take a look at the WSGateway module
WSGateway.ts
|
|
ws-gateway.controller.ts
|
|
ws-gateway.module.ts
Notes:
- In
providers- You need to provide
WSGatewayso that it can be started inapp.module - You need to provide
SHARED_SERVICE, which is the shared service used for injection; you can leave it out if you don’t have one - You need to provide
WS_QUEUE_SERVICE, this is critical; without it,WSGatewaywill only start theWebsocketlistener and will not start the microservice - The above one seems unnecessary; it works fine after removing it, and creating it in
app.moduleis enough
- You need to provide
|
|
app
gateway.controller.ts and gatewary.service.ts are unrelated to this. Previously WSGateway was also injected there, and as a result every connection was triggered twice — effectively starting two WSGateway services.
gateway.module.ts
|
|
main.ts
- You can just create the microservice directly, so creating the microservice in
ws-gateway.module.tsis no longer needed - Because the port
3333is already defined in theWebSocketGatewaydecorator inWSGateway.ts,Websocketwill also start directly; there is no need to callapp.listen(3333)
|
|
Summary
At this point, the client -> websocket -> rabbitmq -> app service -> rabbitmq -> websocket -> client flow works.
I took some detours along the way. NestJS’s documentation doesn’t feel very comprehensive or detailed, and I’m not that familiar with NestJS microservices myself, so it took some time.
A few problems took a lot of time to debug:
- Two
WSGatewayinstances were started, so a connection came in twice; this made theclientsI stored inaccurate, and I couldn’t find the corresponding client socket, so I couldn’t reply to messages - Figuring out how to integrate
WSGatewaywith themicroservicetook some time. The main issue is NestJS’s module architecture: you need toimportwhen necessary, and to use acontrollerfrom an imported module within the current module you need to add it toproviders; if you want other modules to use it, you need to add it toexports.