简体   繁体   English

Rails应用程序内的AMQP订阅者

[英]AMQP subscriber inside Rails app

Is it possible to start an AMQP subscriber with my Rails app? 是否可以使用我的Rails应用程序启动AMQP订阅者? Possibly through an initializer or something. 可能通过初始化器或其他东西。

I'd like to have it running at the same time that can also interact with Rails models. 我想让它同时运行,也可以与Rails模型交互。 Below is a pseudo-code example of what I mean. 下面是我的意思的伪代码示例。

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

I usually do this via a separate messaging daemon which loads the rails environment. 我通常通过一个单独的消息传递守护进程来加载rails环境。

So a very simplistic example would look like this in rails_root/script/myapp_daemon.rb : 所以一个非常简单的例子在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

You would also need the right gem requires in your Gemfile: amqp, daemons, eventmachine 您还需要在Gemfile中使用正确的gem:amqp,daemons,eventmachine

Then either run it manually alongside your app: 然后在您的应用旁边手动运行它:

RAILS_ENV=development script/myapp_daemon.rb run

Or start it from one of your app initializers: 或者从您的某个应用初始值设定项启动它:

system('script/myapp_daemon.rb start')

To dig into amqp check out the following, this will give a nice high level overview: http://www.rubyinside.com/why-rubyists-should-care-about-messaging-a-high-level-intro-5017.html 要深入了解amqp,请查看以下内容,这将提供一个很好的高级概述: http ://www.rubyinside.com/why-rubyists-should-care-about-messaging-a-high-level-intro-5017 。 HTML

This gives a very detailed explanation with working examples: http://rubydoc.info/github/ruby-amqp/amqp/master/file/docs/Exchanges.textile#Publishing_messages_as_immediate_ 这给出了一个非常详细的解释和工作示例: http//rubydoc.info/github/ruby-amqp/amqp/master/file/docs/Exchanges.textile#Publishing_messages_as_immediate_

Finally see if Bunny accomplishes everything you need for the client, it is simpler: https://github.com/celldee/bunny/wiki/Using-Bunny 最后看看Bunny是否能完成客户端所需的一切,更简单: https//github.com/celldee/bunny/wiki/Using-Bunny

Hope that helps 希望有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM