Class: Emq::Sender

Inherits:
Object
  • Object
show all
Defined in:
app/messages/emq/sender.rb

Overview

This class should be responsible for sending messages to the EMQ

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, subject, version) ⇒ Sender

Initialize the sender with the configuration, subject and version

Parameters:

  • config (Hash)

    the configuration for the sender

  • subject (String)

    the subject of the schema that the message is validated against

  • version (String)

    the version of the schema that the message is validated against



14
15
16
17
18
# File 'app/messages/emq/sender.rb', line 14

def initialize(config, subject, version)
  @config = config
  @subject = subject
  @version = version
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'app/messages/emq/sender.rb', line 8

def config
  @config
end

#subjectObject (readonly)

Returns the value of attribute subject.



8
9
10
# File 'app/messages/emq/sender.rb', line 8

def subject
  @subject
end

#versionObject (readonly)

Returns the value of attribute version.



8
9
10
# File 'app/messages/emq/sender.rb', line 8

def version
  @version
end

Instance Method Details

#send_message(message) ⇒ Object

Send a message to the EMQ

Parameters:

  • message (String)

    the message to send



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/messages/emq/sender.rb', line 22

def send_message(message) # rubocop:disable Metrics/MethodLength
  conn = Bunny.new(connection_params)
  conn.start

  begin
    channel = conn.create_channel
    exchange = channel.headers(config.exchange, passive: true)
    headers = { subject:, version:, encoder_type: 'binary' }
    exchange.publish(message, headers:, persistent: true)
  rescue Bunny::TCPConnectionFailed, Bunny::NetworkFailure => e
    # Log the error with message identifier
    Rails.logger.error("Failed to send message with ID #{message.messageUuid}: #{e.message}")
    raise
  ensure
    conn.close
  end
end