Class: Msgr::Dispatcher

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/msgr/dispatcher.rb

Overview

The Dispatcher receives incoming messages, process them through a middleware stack and delegate them to a new and fresh consumer instance.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#log, #log_name

Constructor Details

#initialize(config) ⇒ Dispatcher

Returns a new instance of Dispatcher.



14
15
16
17
18
# File 'lib/msgr/dispatcher.rb', line 14

def initialize(config)
  log(:info) { "Initialize new dispatcher (#{config[:max]} threads)..." }

  @pool = ::Concurrent::CachedThreadPool.new(max: config[:max])
end

Instance Attribute Details

#poolObject (readonly)

Returns the value of attribute pool.



12
13
14
# File 'lib/msgr/dispatcher.rb', line 12

def pool
  @pool
end

Instance Method Details

#call(message) ⇒ Object



20
21
22
23
24
# File 'lib/msgr/dispatcher.rb', line 20

def call(message)
  pool.post(message) do |message|
    dispatch message
  end
end

#dispatch(message) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/msgr/dispatcher.rb', line 26

def dispatch(message)
  consumer_class = Object.const_get message.route.consumer

  log(:debug) { "Dispatch message to #{consumer_class.name}" }

  consumer_class.new.dispatch message

  # Acknowledge message unless it is already acknowledged.
  message.ack unless message.acked?
rescue => error
  log(:error) do
    "Dispatcher error: #{error.class.name}: #{error}\n" +
        error.backtrace.join("\n")
  end
ensure
  if defined?(ActiveRecord) && ActiveRecord::Base.connection_pool.active_connection?
    log(:debug) { 'Release used AR connection for dispatcher thread.' }
    ActiveRecord::Base.connection_pool.release_connection
  end
end

#shutdownObject



47
48
49
# File 'lib/msgr/dispatcher.rb', line 47

def shutdown

end

#to_sObject



51
52
53
# File 'lib/msgr/dispatcher.rb', line 51

def to_s
  self.class.name
end