messageProducer.js 861 B

12345678910111213141516171819202122232425262728293031
  1. const amqp = require('amqplib');
  2. class RabbitMQWrapper {
  3. constructor(connectionURL) {
  4. this.connectionURL = connectionURL;
  5. this.connection = null;
  6. this.channel = null;
  7. }
  8. async connect() {
  9. try {
  10. this.connection = await amqp.connect(this.connectionURL);
  11. this.channel = await this.connection.createChannel();
  12. console.log('Connected to RabbitMQ');
  13. } catch (error) {
  14. console.error('Error connecting to RabbitMQ:', error);
  15. }
  16. }
  17. async publishToQueue(queueName, message) {
  18. try {
  19. await this.channel.assertQueue(queueName, { durable: true });
  20. this.channel.sendToQueue(queueName, Buffer.from(message));
  21. console.log(`Published to ${queueName}: ${message}`);
  22. } catch (error) {
  23. console.error(`Error publishing to ${queueName}:`, error);
  24. }
  25. }
  26. }
  27. module.exports = RabbitMQWrapper;