Class: Watership::Consumer

Inherits:
Object
  • Object
show all
Defined in:
lib/watership/consumer.rb

Instance Method Summary collapse

Constructor Details

#initialize(consumer, url, channel_options = {}, queue_options = {}) ⇒ Consumer

Returns a new instance of Consumer.



5
6
7
8
9
10
11
# File 'lib/watership/consumer.rb', line 5

def initialize(consumer, url, channel_options = {}, queue_options = {})
  @consumer = consumer
  @url = url
  @prefetch = channel_options.delete(:prefetch) || Integer(ENV.fetch("RABBIT_CONSUMER_PREFETCH", 200))
  @channel_opts = {durable: true}.merge(channel_options)
  @queue_opts = {block: true, ack: true}.merge(queue_options)
end

Instance Method Details

#consumeObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/watership/consumer.rb', line 13

def consume
  Thread.abort_on_exception = true
  begin
    queue.subscribe(@queue_opts) do |delivery_info, properties, payload|
      success = false
      begin
        @consumer.call(JSON.parse(payload))
        success = true
      rescue StandardError => exception
        logger.error "Error thrown in subscribe block"
        logger.error exception.message
        logger.error exception.backtrace.join("\n")
        Airbrake.notify(exception) if defined?(AirBrake)
        logger.info "Rejecting in rabbit"
        throw(:terminate)
      rescue Interrupt => exception
        logger.error "Interrupt in subscribe block"
        logger.warn "Stopped gracefully."
        throw(:terminate)
      ensure
        if success
          logger.info "Acking message"
          channel.acknowledge(delivery_info.delivery_tag, false)
        else
          logger.info "Rejecting message"
          channel.reject(delivery_info.delivery_tag, true)
        end
      end
    end
  ensure
    logger.info "Closing Channel"
    channel.close
  end
end