RabbitMQProducer.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const RabbitMQConnector = require('./RabbitMQConnector');
  2. class RabbitMQProducer {
  3. constructor() {
  4. this.connect();
  5. }
  6. async connect() {
  7. this.rabbitmqConnector = new RabbitMQConnector();
  8. await this.rabbitmqConnector.connect();
  9. }
  10. async disconnect() {
  11. await this.rabbitmqConnector.disconnect();
  12. }
  13. async publishToQueue(queueName, message) {
  14. if(this.rabbitmqConnector.channel === null) {
  15. await this.connect();
  16. }
  17. try {
  18. await this.rabbitmqConnector.channel.assertQueue(queueName, { durable: true });
  19. this.rabbitmqConnector.channel.sendToQueue(queueName, Buffer.from(message));
  20. console.log(`Published to ${queueName}: ${message}`);
  21. } catch (error) {
  22. console.error(`Error publishing to ${queueName}:`, error);
  23. }
  24. }
  25. async sendMessage(queueName, message) {
  26. try {
  27. await this.publishToQueue(queueName, message);
  28. } catch (error) {
  29. console.error('Error sending message:', error.message);
  30. }
  31. }
  32. }
  33. module.exports = RabbitMQProducer;