Created
April 18, 2011 23:10
-
-
Save ezmobius/926485 to your computer and use it in GitHub Desktop.
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 'sinatra' | |
require 'pp' | |
require 'redis' | |
require 'json' | |
configure do | |
redis = JSON.parse(ENV['VMC_SERVICES']).select {|srvc| srvc['name'] =~ /redis-.*?/ }.first['options'] | |
redis_conf = {:host => redis['hostname'], :port => redis['port'], :password => redis['password']} | |
@@redis = Redis.new redis_conf | |
@@redis_ps = Redis.new redis_conf | |
@@subs_setup = false | |
end | |
helpers do | |
def setup_subs(*subs) | |
@@subs_setup = true | |
@@redis_ps.subscribe(*subs) do |on| | |
on.subscribe {|queue, num_subs| puts "Subscribed to #{queue} (#{num_subs} subscriptions)" } | |
on.message do |queue, msg| | |
begin | |
process_message(queue, msg) | |
rescue => e | |
p [:ERROR, e.message] | |
end | |
end | |
on.unsubscribe {|queue, num_subs| puts "Unsubscribed to #{queue} (#{num_subs} subscriptions)" } | |
end | |
end | |
def publish(queue, msg) | |
@@redis.publish(queue, msg.to_json) | |
end | |
end | |
before do | |
if ! @@subs_setup | |
Thread.new do | |
setup_subs('return', 'foo', 'bar') | |
@@subs_setup = true | |
end | |
end | |
end | |
get '/' do | |
@foos = @@redis.smembers('redis-worker:foos') rescue [] | |
@bars = @@redis.smembers('redis-worker:bars') rescue [] | |
erb :index | |
end | |
post "/work" do | |
puts "submitting job for work" | |
if ['foo', 'bar'].include?(params[:queue]) | |
publish(params[:queue], :value => params[:value]) | |
end | |
redirect "/" | |
end | |
def process_message(queue, msg) | |
msg = JSON.parse(msg) | |
case queue | |
when 'return' | |
process_return(msg) | |
when 'foo' | |
work_on_foo(msg) | |
when 'bar' | |
work_on_bar(msg) | |
end | |
end | |
def work_on_foo(msg) | |
puts "working on foo: #{msg.inspect}" | |
# do some work | |
publish('return', 'from' => 'foo', 'value' => msg['value']) | |
end | |
def work_on_bar(msg) | |
puts "working on bar: #{msg.inspect}" | |
# do some work | |
publish('return', 'from' => 'bar','value' => msg['value']) | |
end | |
def process_return(msg) | |
case msg['from'] | |
when 'foo' | |
puts "processed a foo" | |
@@redis.sadd 'redis-worker:foos', msg['value'] | |
when 'bar' | |
puts "processed a bar" | |
@@redis.sadd 'redis-worker:bars', msg['value'] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment