local amqp = require "amqp" local RabbitMQPublisher = {} function RabbitMQPublisher.connectWithRetries(connectionParams, retryInterval, maxRetries) local conn for attempt = 1, maxRetries do conn = amqp:new({ role = connectionParams.role, queue = connectionParams.queue, exchange = connectionParams.exchange, ssl = connectionParams.ssl, user = connectionParams.username, password = connectionParams.password }) local success, err = conn:connect(connectionParams.host, connectionParams.port) if success then session:consoleLog("info", "Connected to RabbitMQ") return conn else session:consoleLog("info" ,"Connection attempt " .. attempt .. " failed. Retrying in " .. retryInterval .. " seconds...") os.execute("sleep " .. retryInterval) end end session:consoleLog("error", "Failed to connect to RabbitMQ after " .. maxRetries .. " attempts.") error("Failed to connect to RabbitMQ after " .. maxRetries .. " attempts.") end function RabbitMQPublisher.publishMessage(conn, message, queueName, routingKey) local channel = conn:create_channel() local queue = channel:queue_declare(queueName, { durable = true, auto_delete = false, exclusive = false, }) channel:basic_publish("", routingKey, message) channel:close() end function RabbitMQPublisher.closeConnection(conn) if conn then conn:close() end end return RabbitMQPublisher I'm using this with these local connectionParams = { host = "localhost", port = 5672, username = "guest", password = "guest", vhost = "/", role = "publisher", exchange = 'exchange', ssl = false, } -- Connect to RabbitMQ with retries local conn = RabbitMQPublisher.connectWithRetries(connectionParams, 5, 3) RabbitMQPublisher.publishMessage(conn, json_message, routingKey) -- Close the RabbitMQ connection RabbitMQPublisher.closeConnection(conn)