Class: ChiliLogger::RabbitBroker

Inherits:
Object
  • Object
show all
Defined in:
lib/brokers/rabbit_broker.rb

Overview

class that configures and manages the RabbitMQ client

Instance Method Summary collapse

Constructor Details

#initialize(custom_config = {}) ⇒ RabbitBroker

Returns a new instance of RabbitBroker.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/brokers/rabbit_broker.rb', line 9

def initialize(custom_config = {})
  custom_config ||= {}
  config = rabbit_config(custom_config)

  @user = config[:user]
  @password = config[:password]
  @ip = config[:ip]
  @port = config[:port]
  @exchange_name = config[:exchange_name]
  @routing_key_overwriter = custom_config[:routing_key_overwriter]

  connect
end

Instance Method Details

#connectObject



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/brokers/rabbit_broker.rb', line 23

def connect
  return if ChiliLogger.instance.deactivated

  @connection = Bunny.new(connection_config)
  @connection.start

  @channel = @connection.create_channel
  @exchange = @channel.topic(@exchange_name, durable: true)
rescue StandardError => e
  puts 'Could not connect to RabbitMQ due to the following error:'
  puts e
end

#publish(message) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/brokers/rabbit_broker.rb', line 36

def publish(message)
  return if ChiliLogger.instance.deactivated

  # if no routing_key was provided when configuring RabbitBroker, than use the message's description tag
  key = @routing_key_overwriter || message[:desc] || message['desc']
  @exchange.publish(message.to_json, routing_key: key)
  puts "sent message to #{@exchange_name}, with routing_key = '#{key}'"
end