Created
July 14, 2014 21:36
-
-
Save esmevane/5f65254059fd8abe42e0 to your computer and use it in GitHub Desktop.
[ Ruby / Bunny / RabbitMQ ]: Lightweight Resque interface made via MessageQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bunny' | |
require 'json' | |
require 'pry' | |
class MessageQueue | |
attr_reader :channel, :service, :queue | |
def initialize(service, channel) | |
@channel = channel | |
@service = service | |
@queue = service.create_channel.queue(channel, durable: true) | |
end | |
def enqueue(klass, *args) | |
pub(class: klass, args: args) | |
end | |
def work(channel_name = channel) | |
service.with_channel do |service_channel| | |
ServiceWorker.new(channel_name, service_channel).perform | |
end | |
end | |
private | |
def pub(message) | |
queue.publish(message.to_json, | |
content_type: 'application/json', | |
persistent: true | |
) | |
end | |
class ServiceWorker | |
attr_reader :channel_name, :local_queue, :service_channel | |
def initialize(channel_name, service_channel) | |
@channel_name = channel_name | |
@service_channel = service_channel | |
@local_queue = service_channel.queue channel_name, durable: true | |
end | |
def perform | |
local_queue.subscribe(ack: true, block: true) do |delivery, _, payload| | |
begin | |
payload = JSON.parse payload, symbolize_names: true | |
job = Kernel.const_get(payload.fetch(:class)) | |
job.perform(*payload.fetch(:args)) | |
service_channel.acknowledge(delivery.delivery_tag, false) | |
rescue Exception => e | |
service_channel.reject(delivery.delivery_tag, false) | |
end | |
end | |
end | |
end | |
end | |
class Derper | |
def self.perform(*derpies) | |
derpies.each { |derp| puts derp.inspect } | |
end | |
end | |
BUNNY = Bunny.new 'amqp://guest:guest@localhost' | |
BUNNY.start | |
MESSAGES = MessageQueue.new BUNNY, "application_name" | |
def do_the_derp(derps = 10) | |
MESSAGES.enqueue Derper, *["Derp"]*derps | |
end | |
do_the_derp | |
MESSAGES.work |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment