Module: Sidekiq::Middleware

Defined in:
lib/sidekiq/middleware/chain.rb

Overview

Middleware is code configured to run before/after a job is processed. It is patterned after Rack middleware. Middleware exists for the client side (pushing jobs onto the queue) as well as the server side (when jobs are actually processed).

Callers will register middleware Classes and Sidekiq will create new instances of the middleware for every job. This is important so that instance state is not shared accidentally between job executions.

To add middleware for the client:

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.add MyClientHook
  end
end

To modify middleware for the server, just call with another block:

Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add MyServerHook
    chain.remove ActiveRecord
  end
end

To insert immediately preceding another entry:

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.insert_before ActiveRecord, MyClientHook
  end
end

To insert immediately after another entry:

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.insert_after ActiveRecord, MyClientHook
  end
end

This is an example of a minimal server middleware:

class MyServerHook
  include Sidekiq::ServerMiddleware

  def call(job_instance, msg, queue)
    logger.info "Before job"
    redis {|conn| conn.get("foo") } # do something in Redis
    yield
    logger.info "After job"
  end
end

This is an example of a minimal client middleware, note the method must return the result or the job will not push to Redis:

class MyClientHook
  include Sidekiq::ClientMiddleware

  def call(job_class, msg, queue, redis_pool)
    logger.info "Before push"
    result = yield
    logger.info "After push"
    result
  end
end

Defined Under Namespace

Classes: Chain