Skip to content

Instantly share code, notes, and snippets.

Created March 12, 2019 15:59
What would you like to do?
Ruby consumer for RabbitMQ queue with rate-limiting based on Redis
#!/usr/bin/env ruby
# encoding utf-8
require 'bunny'
require 'logger'
require 'redis'
logger =
STDOUT.sync = true
conn = 'rmq', user: 'guest', pass: 'guest')
ch = conn.create_channel
q = ch.queue('work.queue', arguments: { :'x-dead-letter-exchange' => '' })
Redis.current = 'redis')
# `block: true` is only for presentation purposes
# it blocks the main thread, do not use it in production
q.subscribe(manual_ack: true, block: true) do |delivery_info, properties, payload| "Message received with payload: #{payload}"
key = "slot:#{}"
slot = Redis.current.get(key) "Slot value: #{slot}"
if !slot || slot.to_i < 1 "Slot acquired, writing to Redis"
result = Redis.current.multi do |multi|
multi.set(key, 1)
multi.expire(key, 1)
end "Slot acquired, finished writing to Redis with result: #{result}"
ch.ack(delivery_info.delivery_tag) "Message acked"
# reject without requeue
ch.reject(delivery_info.delivery_tag) "Message rejected"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment