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(logging_error_handler) ⇒ RabbitBroker

Returns a new instance of RabbitBroker.



8
9
10
# File 'lib/brokers/rabbit_broker.rb', line 8

def initialize(logging_error_handler)
  @logging_error_handler = logging_error_handler
end

Instance Method Details

#config(config) ⇒ Object



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

def config(config)
  validate_config(config)

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

  connect
end

#connectObject



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

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

#disconnectObject



39
40
41
# File 'lib/brokers/rabbit_broker.rb', line 39

def disconnect
  @connection.close
end

#publish(message, routing_key) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/brokers/rabbit_broker.rb', line 43

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

  # if no routing_key was provided when configuring RabbitBroker, than use the one received by the method here
  # temporary solution so we can force configure ChiliLogger to use a specific routing_key
  key = @routing_key_overwriter || routing_key
  @exchange.publish(message.to_json, routing_key: key)
  puts "sent message to #{@exchange_name}, with routing_key = '#{key}'"

rescue StandardError => e
  @logging_error_handler.handle_error(e, message)
end