Class: Emque::Producing::Publisher::RabbitMq

Inherits:
Base
  • Object
show all
Defined in:
lib/emque/producing/publisher/rabbitmq.rb

Constant Summary collapse

CONN =
Bunny
.new(Emque::Producing.configuration.rabbitmq_options[:url])
.tap { |conn|
  conn.start
}
CHANNEL_POOL =
Queue
.new
.tap { |queue|
  20.times { |i| queue << CONN.create_channel }
}

Instance Method Summary collapse

Methods inherited from Base

#handle_error, #host_name

Instance Method Details

#publish(topic, message_type, message, key = nil) ⇒ Object



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
47
48
49
50
51
52
53
54
# File 'lib/emque/producing/publisher/rabbitmq.rb', line 20

def publish(topic, message_type, message, key = nil)
  ch = CHANNEL_POOL.pop
  ch.open if ch.closed?
  begin
    exchange = ch.fanout(topic, :durable => true, :auto_delete => false)

    # Assumes all messages are mandatory in order to let callers know if
    # the message was not sent. Uses publisher confirms to wait.
    ch.confirm_select
    sent = true
    exchange.on_return do |return_info, properties, content|
      sent = false
    end

    exchange.publish(
      message,
      :mandatory => true,
      :persistent => true,
      :type => message_type,
      :app_id => Emque::Producing.configuration.app_name,
      :content_type => "application/json")

    success = ch.wait_for_confirms
    unless success
      Emque::Producing.logger.warn("RabbitMQ Publisher: message was nacked")
      ch.nacked_set.each do |n|
        Emque::Producing.logger.warn("message id: #{n}")
      end
    end

    return sent
  ensure
    CHANNEL_POOL << ch unless ch.nil?
  end
end