Created
April 29, 2014 11:11
-
-
Save eljojo/11397116 to your computer and use it in GitHub Desktop.
simple redis queue. it might have bugs.
This file contains hidden or 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
class SimpleQueue | |
def initialize(name) | |
@name = name.to_sym | |
end | |
def push(items) | |
return unless items.present? | |
items = [items] unless items.is_a?(Array) | |
with_redis do |redis| | |
redis.sadd(redis_key, items.map(&:to_s)) | |
end | |
end | |
def pop(count = 1) | |
l = length | |
count = l if count > l | |
with_redis do |redis| | |
count.times.map do | |
redis.spop(redis_key) | |
end | |
end | |
end | |
def length | |
with_redis do |redis| | |
redis.scard(redis_key) | |
end | |
end | |
private | |
delegate :with_redis, to: :class | |
def redis_key | |
@redis_key ||= "simple_queue:#{@name}" | |
end | |
class << self | |
def redis_pool | |
if defined?(Sidekiq) | |
Sidekiq.redis_pool | |
else | |
raise "We currently use sidekiq's connection pool :(" | |
end | |
end | |
def with_redis(&block) | |
raise ArgumentError, "requires a block" if !block | |
redis_pool.with(&block) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment