是否可以从Delayed Job调用Bunny :: Exchange发布?

时间:2017-05-19 13:06:24

标签: ruby-on-rails rabbitmq delayed-job bunny

我有一个Rails应用程序,有时使用gem" Bunny"将消息发布到RabbitMQ队列。这是设置:

# config/initializers/bunny.rb
$mq_connection = Bunny.new
$mq_connection.start
$mq_channel = $mq_connection.create_channel

应用程序中的任何地方我都可以致电:

exchange = $mq_channel.default_exchange
exchange.publish(msg.to_json, persistent: true, routing_key: '...')

如果我从应用程序或控制台调用它,那么这很有效,但如果从DelayedJob作业调用,它就会起作用。没有引发异常,但是没有发送消息。

尝试使用单身人士:

看起来像$mq_channel这样的全局变量无法被DelayedJob找到,所以我创建了一个单例模型来存储它:

class RabbitMq
  include Singleton

  attr_accessor :connection, :channel

  def exchange
    channel.default_exchange
  end

  def setup
    self.connection = Bunny.new
    self.connection.start
    self.channel = connection.create_channel
  end

end

我从初始化程序调用设置:

# config/initializers/bunny.rb
RabbitMq.instance.setup

但这并不奏效。作业终止没有错误,但没有发布。

知道怎么做吗?从像DJ这样的后台工作者向RabbitMQ发布消息应该是很常见的。

1 个答案:

答案 0 :(得分:2)

我是这样做的:

class Messaging::Publisher

  class << self

    def publish(message)
      new(message).publish
    end

  end # Class Methods

  #=========================================================================
  # Instance Methods      
  #=========================================================================

    def initialize(message)
      @message = message
    end

    def publish
      connection = Bunny.new(ENV['CLOUDAMQP_URL'])
      connection.start
      channel = connection.create_channel
      queue_name = "#{ENV['app_name']}.#{message.keys.first.to_s.pluralize}_queue"
      queue = channel.queue(queue_name, durable: true)
      channel.default_exchange.publish(message.to_json, :routing_key => queue.name)
      channel.close
      connection.stop
      true
    end

  private

    def message()   @message    end

end

我从我的应用程序(同步)和后台作业(异步)中调用它。像这样:

class ServiceRequests::CreateManager < ServiceRequests::ManagerBase

  class << self

  private

  end # Class Methods

  #=========================================================================
  # Instance Methods
  #=========================================================================

    def manage
      Messaging::Publisher.publish service_request_message
    end

  private

    def service_request_message
      {
        service_request: {
          provider: {
            name: "Foo::Bar"
          },
          params: {
            baz: 'qux'
          }
        }
      }
    end

end