Skip to content

Middleware

phstc edited this page Oct 26, 2014 · 12 revisions

Basic usage

class MyMiddleware
  def call(worker_instance, queue, sqs_msg, body)
    puts 'Before work'
    yield
    puts 'After work'
  end
end

Enabling a middleware

Shoryuken.configure_server do |config|
  config.server_middleware do |chain|
    chain.add MyMiddleware
    # chain.remove MyMiddleware
    # chain.insert_before MyMiddleware, MyMiddlewareNew
    # chain.insert_after MyMiddleware, MyMiddlewareNew
  end
end

Rejecting the message consumption

You can omit the yield call in case you want to reject a message consumption.

class RejectInvalidMessagesMiddleware
  def call(worker_instance, queue, sqs_msg, body)
    if valid?(sqs_msg)
      # will consume the message
      yield
    else
      # will not consume the message
      Shoryuken.logger.info "sqs_msg '#{sqs_msg.id}' is invalid and was rejected"
      sqs_msg.delete
    end
  end
end

Batchable workers

Be careful with batchable workers, because when they are used the sqs_msg and body arguments are arrays.

class DoSomethingMiddleware
  def call(worker_instance, queue, sqs_msg, body)
    # if you want to skip batchable workers
    # if sqs_msg.is_a? Array
    #   yield
    #   return
    # end

    # if you want to process batchable and not batchabled in the same way
    Array(sqs_msg).each_with_index do |current_sqs_msg, index|
      current_body = body[index]

      # do_something(current_sqs_msg, current_body)
    end

    yield
  end
end
Clone this wiki locally