【问题标题】:AMQP subscriber inside Rails appRails 应用程序中的 AMQP 订阅者
【发布时间】:2010-05-14 15:00:31
【问题描述】:

是否可以使用我的 Rails 应用程序启动 AMQP 订阅者?可能通过初始化程序或其他方式。

我想让它同时运行,它还可以与 Rails 模型交互。下面是我的意思的伪代码示例。

queue.subscribe do |msg,body|
  Foo.create(....)
end

【问题讨论】:

  • 我想知道您决定从哪里获得订阅、初始化程序或其他地方?

标签: ruby-on-rails rabbitmq amqp


【解决方案1】:

我通常通过加载 rails 环境的单独消息传递守护进程来执行此操作。

因此,rails_root/script/myapp_daemon.rb 中的一个非常简单的示例如下所示:



    #!/usr/bin/env ruby
    require 'rubygems'
    require 'amqp'
    require 'daemons'

    ENV["RAILS_ENV"] ||= "development"
    require File.dirname(__FILE__) + "/../config/environment"

    options = { :backtrace => true, :dir => '.', :log_output => true}

    Daemons.run_proc('myapp_daemon', options) do
      EventMachine.run do
        connection = AMQP.connect(:host => "127.0.0.1")

        channel = AMQP::Channel.new(connection)
        queue    = channel.queue("/myapp_daemon", :durable => true)
        exchange = channel.direct("")

        queue.subscribe do |payload|
          obj = JSON.parse(payload)
          #... handle messages here, utilize your rails models
          Foo.create(...)
        end
      end
    end

您的 Gemfile 中还需要正确的 gem:amqp、daemons、eventmachine

然后在您的应用旁边手动运行它:

RAILS_ENV=development script/myapp_daemon.rb run

或从您的应用初始化程序之一启动它:

system('script/myapp_daemon.rb start')

要深入了解 amqp,请查看以下内容,这将提供一个很好的高级概述: http://www.rubyinside.com/why-rubyists-should-care-about-messaging-a-high-level-intro-5017.html

这通过工作示例给出了非常详细的解释: http://rubydoc.info/github/ruby-amqp/amqp/master/file/docs/Exchanges.textile#Publishing_messages_as_immediate_

最后看看Bunny是否为客户完成了你需要的一切,比较简单: https://github.com/celldee/bunny/wiki/Using-Bunny

希望有帮助

【讨论】:

  • 看看你的实现,它会递归启动守护进程吗?
  • 请注意,从初始化程序开始将在 Rails 控制台上启动它,通常是启动应用程序的所有内容。
猜你喜欢
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 2018-10-19
相关资源
最近更新 更多