Skip to content

Instantly share code, notes, and snippets.

@maintux
Created September 28, 2015 12:15
Show Gist options
  • Select an option

  • Save maintux/3ba1bb6ebbed53727cf8 to your computer and use it in GitHub Desktop.

Select an option

Save maintux/3ba1bb6ebbed53727cf8 to your computer and use it in GitHub Desktop.
redis_smtp_scheduler.rb
require 'rubygems'
require 'redis'
r = Redis.new(:host => "127.0.0.1", :port => 6379, :db => 5)
r.multi do
r.del 'smtp_servers'
r.del 'smtp_servers_conf'
r.rpush 'smtp_servers', 11
r.rpush 'smtp_servers', 12
r.rpush 'smtp_servers', 13
r.hmset 'smtp_servers_conf', 11, 3, 12, 1, 13, 2
r.hmset 'smtp_status', 'current', 0, 'sent', 0
end
NextSMTPScript = <<EOF
local current = redis.call('hget', 'smtp_status', 'current')
local sent = redis.call('hget', 'smtp_status', 'sent')
local current_id = redis.call('lindex', 'smtp_servers', current)
local max = redis.call('hget', 'smtp_servers_conf', current_id)
local res
if sent == max then
local new_current = current + 1
local server_size = redis.call('llen', 'smtp_servers')
if new_current == server_size then
new_current = 0
end
res = redis.call('lindex', 'smtp_servers', new_current)
redis.call('hmset', 'smtp_status', 'current', new_current, 'sent', 0)
else
res = current_id
end
redis.call('hincrby', 'smtp_status', 'sent', 1)
return res
EOF
sha1 = r.script :load, NextSMTPScript
puts r.evalsha(sha1,[])
# => 11
puts r.evalsha(sha1,[])
# => 11
puts r.evalsha(sha1,[])
# => 11
puts r.evalsha(sha1,[])
# => 12
puts r.evalsha(sha1,[])
# => 13
puts r.evalsha(sha1,[])
# => 13
puts r.evalsha(sha1,[])
# => 11
puts r.hgetall 'smtp_status'
# => {"current"=>"0", "sent"=>"1"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment