From Tomi Hakkarainen, 7 Months ago, written in FreeSWITCH.
- view diff
Embed
  1. local amqp = require "amqp"
  2.  
  3. local RabbitMQPublisher = {}
  4.  
  5. function RabbitMQPublisher.connectWithRetries(connectionParams, retryInterval, maxRetries)
  6.     local conn
  7.     for attempt = 1, maxRetries do
  8.         conn = amqp:new({
  9.             role = connectionParams.role,
  10.             queue = connectionParams.queue,
  11.             exchange = connectionParams.exchange,
  12.             ssl = connectionParams.ssl,
  13.             user = connectionParams.username,
  14.             password = connectionParams.password
  15.         })
  16.         local success, err = conn:connect(connectionParams.host, connectionParams.port)
  17.         if success then
  18.             session:consoleLog("info", "Connected to RabbitMQ")
  19.             return conn
  20.         else
  21.             session:consoleLog("info" ,"Connection attempt " .. attempt .. " failed. Retrying in " .. retryInterval .. " seconds...")
  22.             os.execute("sleep " .. retryInterval)
  23.         end
  24.     end
  25.    session:consoleLog("error", "Failed to connect to RabbitMQ after " .. maxRetries .. " attempts.")
  26.    error("Failed to connect to RabbitMQ after " .. maxRetries .. " attempts.")
  27. end
  28.  
  29. function RabbitMQPublisher.publishMessage(conn, message, queueName, routingKey)
  30.     local channel = conn:create_channel()
  31.     local queue = channel:queue_declare(queueName, {
  32.                                                     durable = true,
  33.                                                     auto_delete = false,
  34.                                                     exclusive = false,
  35.                                                     })
  36.     channel:basic_publish("", routingKey, message)
  37.     channel:close()
  38. end
  39.  
  40. function RabbitMQPublisher.closeConnection(conn)
  41.     if conn then
  42.         conn:close()
  43.     end
  44. end
  45.  
  46. return RabbitMQPublisher
  47.  
  48.  
  49.  
  50. I'm using this with these
  51.  
  52.  
  53. local connectionParams = {
  54.   host = "localhost",
  55.   port = 5672,
  56.   username = "guest",
  57.   password = "guest",
  58.   vhost = "/",
  59.   role = "publisher",
  60.   exchange = 'exchange',
  61.   ssl = false,
  62. }
  63.  
  64. -- Connect to RabbitMQ with retries
  65. local conn = RabbitMQPublisher.connectWithRetries(connectionParams, 5, 3)
  66.  
  67.  
  68. RabbitMQPublisher.publishMessage(conn, json_message, routingKey)
  69.  
  70.     -- Close the RabbitMQ connection
  71. RabbitMQPublisher.closeConnection(conn)