Class: RabbitMQ::Actors::TopicConsumer Abstract

Inherits:
Base::Consumer show all
Defined in:
lib/rabbitmq/actors/patterns/topics/topic_consumer.rb

Overview

This class is abstract.

Subclass and override #perform to define your customized topic worker class.

A consumer of messages from RabbitMQ based on exchange and routing key matching patterns.

Examples:

class SpainTennisListener < RabbitMQ::Actors::TopicConsumer
  def initialize
    super(topic_name:      'sports',
          binding_keys:    '#.tennis.#.spain.#',
          logger:          Rails.logger,
          on_cancellation: ->{ ActiveRecord::Base.connection.close })
  end

  private

  def perform(**task)
    match_data = JSON.parse(task[:body])
    process_tennis_match(match_data)
  end

  def process_tennis_match(data)
    ...
  end
end

class AmericaSoccerListener < RabbitMQ::Actors::TopicConsumer
  def initialize
    super(exchange_name:   'sports',
          binding_keys:    '#.soccer.#.america.#',
          logger:          Rails.logger,
          on_cancellation: ->{ ActiveRecord::Base.connection.close })
  end

  private

  def perform(**task)
    match_data = JSON.parse(task[:body])
    process_soccer_match(match_data)
  end

  def process_soccer_match(data)
    ...
  end
end

RabbitMQ::Server.url = 'amqp://localhost'

SpainTennisListener.new.start!
AmericaSoccerListener.new.start!

Instance Attribute Summary collapse

Attributes inherited from Base::Agent

#queue

Instance Method Summary collapse

Methods inherited from Base::Consumer

#start!

Constructor Details

#initialize(topic_name:, binding_keys: '#', **opts) ⇒ TopicConsumer

Rest of options required by your subclass.

Parameters:

  • :topic_name (String)

    name of the topic exchange this worker will receive messages.

  • :binding_keys (String, Array)

    routing key patterns this worker is interested in. Default to all: ‘#’

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :on_cancellation (Proc)

    to be executed before the worker is terminated

  • :logger (Logger)

    the logger where to output info about this agent’s activity.



69
70
71
# File 'lib/rabbitmq/actors/patterns/topics/topic_consumer.rb', line 69

def initialize(topic_name:, binding_keys: '#', **opts)
  super(opts.merge(topic_name: topic_name, binding_keys: binding_keys))
end

Instance Attribute Details

#binding_keysObject (readonly)

Returns the value of attribute binding_keys.



61
62
63
# File 'lib/rabbitmq/actors/patterns/topics/topic_consumer.rb', line 61

def binding_keys
  @binding_keys
end

#topic_nameObject (readonly)

Returns the value of attribute topic_name.



57
58
59
# File 'lib/rabbitmq/actors/patterns/topics/topic_consumer.rb', line 57

def topic_name
  @topic_name
end