RabbitMQProducer.js 1.1 KB

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