Skip to content

Instantly share code, notes, and snippets.

@julien-sarazin
Created October 22, 2021 07:13
Show Gist options
  • Save julien-sarazin/f884f28a2d59f37ff22227f64ff7f2a5 to your computer and use it in GitHub Desktop.
Save julien-sarazin/f884f28a2d59f37ff22227f64ff7f2a5 to your computer and use it in GitHub Desktop.
RabbitMQ/AMQP Helper - SendToQueue Typescript
import amqp, { Channel, Connection } from 'amqplib';
export class AMQPHelper {
private connection?: Connection;
private channel?: Channel;
constructor(private readonly url: string)
{}
public async sendToQueue (queueName: string, data: string) {
if (!this.connection) {
await this.connect();
}
await this.channel?.assertQueue(queueName);
await this.channel?.sendToQueue(queueName, Buffer.from(data))
}
private async connect() {
this.connection = await amqp.connect(this.url);
this.channel = await this.connection.createChannel();
}
}
@prav-raghu
Copy link

prav-raghu commented Jul 14, 2022

Hi do you have a helper function that listens in on a queue 🙂I've tried the following but it never seems to listen

public async receive() {
var queue = "pingQueue";

    this.channel?.assertQueue(queue, {
        durable: false,
    });

    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);

    this.channel?.consume(
        queue,
        function (msg) {
            console.log(" [x] Received %s", msg?.content.toString());
        },
        {
            noAck: true,
        },
    );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment