2012-01-21 19:42:21 -05:00
|
|
|
require 'multi_json'
|
2012-01-22 14:32:38 -05:00
|
|
|
require 'redis'
|
2012-01-21 19:42:21 -05:00
|
|
|
|
2012-02-08 17:43:57 -05:00
|
|
|
require 'sidekiq/redis_connection'
|
2012-02-08 20:04:02 -05:00
|
|
|
require 'sidekiq/middleware/chain'
|
2012-02-09 23:32:59 -05:00
|
|
|
require 'sidekiq/middleware/client/resque_web_compatibility'
|
2012-02-08 20:04:02 -05:00
|
|
|
require 'sidekiq/middleware/client/unique_jobs'
|
|
|
|
|
2012-01-21 19:42:21 -05:00
|
|
|
module Sidekiq
|
|
|
|
class Client
|
2012-02-10 23:20:01 -05:00
|
|
|
|
2012-02-08 20:04:02 -05:00
|
|
|
def self.middleware
|
2012-02-10 23:20:01 -05:00
|
|
|
@middleware ||= begin
|
|
|
|
m = Middleware::Chain.new
|
|
|
|
m.register do
|
|
|
|
use Middleware::Client::UniqueJobs, Client.redis
|
|
|
|
use Middleware::Client::ResqueWebCompatibility, Client.redis
|
|
|
|
end
|
|
|
|
m
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.queues
|
2012-02-15 13:58:14 -05:00
|
|
|
@queues ||= {}
|
2012-02-07 06:29:09 -05:00
|
|
|
end
|
|
|
|
|
2012-01-21 19:42:21 -05:00
|
|
|
def self.redis
|
2012-02-10 23:20:01 -05:00
|
|
|
@redis ||= RedisConnection.create
|
2012-01-21 19:42:21 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.redis=(redis)
|
|
|
|
@redis = redis
|
|
|
|
end
|
|
|
|
|
|
|
|
# Example usage:
|
2012-01-23 15:56:49 -05:00
|
|
|
# Sidekiq::Client.push('my_queue', 'class' => MyWorker, 'args' => ['foo', 1, :bat => 'bar'])
|
2012-02-10 23:20:01 -05:00
|
|
|
def self.push(queue=nil, item)
|
2012-01-24 17:53:36 -05:00
|
|
|
raise(ArgumentError, "Message must be a Hash of the form: { 'class' => SomeClass, 'args' => ['bob', 1, :foo => 'bar'] }") unless item.is_a?(Hash)
|
2012-01-23 15:56:49 -05:00
|
|
|
raise(ArgumentError, "Message must include a class and set of arguments: #{item.inspect}") if !item['class'] || !item['args']
|
2012-01-21 19:42:21 -05:00
|
|
|
|
2012-02-10 23:20:01 -05:00
|
|
|
queue = queue || queues[item['class'].to_s] || 'default'
|
|
|
|
|
2012-01-23 15:56:49 -05:00
|
|
|
item['class'] = item['class'].to_s if !item['class'].is_a?(String)
|
2012-02-10 23:20:01 -05:00
|
|
|
|
|
|
|
pushed = false
|
2012-02-09 12:24:57 -05:00
|
|
|
middleware.invoke(item, queue) do
|
2012-02-08 20:04:02 -05:00
|
|
|
redis.rpush("queue:#{queue}", MultiJson.encode(item))
|
2012-02-10 23:20:01 -05:00
|
|
|
pushed = true
|
2012-02-07 06:29:09 -05:00
|
|
|
end
|
2012-02-10 23:20:01 -05:00
|
|
|
pushed
|
2012-01-21 19:42:21 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
# Please use .push if possible instead.
|
|
|
|
#
|
|
|
|
# Example usage:
|
|
|
|
#
|
|
|
|
# Sidekiq::Client.enqueue(MyWorker, 'foo', 1, :bat => 'bar')
|
|
|
|
#
|
2012-02-09 23:32:59 -05:00
|
|
|
# Messages are enqueued to the 'default' queue.
|
2012-01-21 19:42:21 -05:00
|
|
|
#
|
|
|
|
def self.enqueue(klass, *args)
|
2012-02-10 23:20:01 -05:00
|
|
|
push(nil, { 'class' => klass.name, 'args' => args })
|
2012-01-21 19:42:21 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|