Search code examples
angulartypescriptrabbitmqnestjs

Nestjs RabbitMQ can't send to queue


I know there are similar questions, but non have worked for me so far. I have a NestJS project which is suposed to get a HTTP-request and send this to a RabbitMQ. The RabbitMQ is setup and a listening C# script can connect to it. I see the connection in the web interface on RabbitMQ. But when I call the function sendIntoQueue() in the AppService nothing happens. No So where am I missing somthing?

This App does not recive anything, and that is rigth. It should only send to the queue. There for the main() should look right?

These are my files:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.listen(3000);
}
bootstrap();
import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { ClientsModule, Transport } from "@nestjs/microservices";


const user = 'quest';
const password = 'quest';
const host = '127.0.0.1:5672';
const queueName = 'dev';
@Module({
  imports: [
    ClientsModule.registerAsync([
      {
        name: "RMQ_CLIENT",
        imports: [],
        useFactory: () => ({
          transport: Transport.RMQ,
          options: {
            urls: [`amqp://${user}:${password}@${host}`],
            queue: queueName,
            queueOptions: {
              durable: false,
            },
          },
        }),
      }
    ])
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
import { Inject, Injectable } from "@nestjs/common";
import { PdfRequest } from "./model/pdf-request";
import { ClientProxy } from "@nestjs/microservices";
import { PdfEvent } from "./events/pdf-event";
import { PdfEventPattern } from "./events/pdf-event-pattern";

@Injectable()
export class AppService {
  private readonly queue: any[] = [];

  constructor(@Inject("RMQ_CLIENT") private readonly pdfClient: ClientProxy) {
  }

  async sendIntoQueue(pdfRequest: PdfRequest) {
    try {
      this.queue.push(pdfRequest);
      let result = this.pdfClient.send("test", {"test": "test"});
    } catch (e){
      console.log(e);
    }
  }
}


Solution

  • Your problem likely is send returns an rxjs Observable, but you are discarding it and it is never subscribed to. The pattern used could be

    this.pdfClient
       .send("test", {"test": "test"})
       .subscribe(response => {
           console.log('Response:', JSON.stringify(response));
      });