问题描述
是否可以通过我的Rails应用启动AMQP订户?可能通过初始化程序之类的东西.
Is it possible to start an AMQP subscriber with my Rails app? Possibly through an initializer or something.
我想让它同时运行,并且还可以与Rails模型进行交互.下面是我的意思的伪代码示例.
I'd like to have it running at the same time that can also interact with Rails models. Below is a pseudo-code example of what I mean.
queue.subscribe do |msg,body|
Foo.create(....)
end
推荐答案
我通常通过加载Rails环境的单独消息传递守护程序来做到这一点.
I usually do this via a separate messaging daemon which loads the rails environment.
因此,在rails_root/script/myapp_daemon.rb中,一个非常简单的示例如下所示:
So a very simplistic example would look like this in 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,守护程序,eventmachine
You would also need the right gem requires in your Gemfile: 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')
要深入研究amqp,请查看以下内容,这将提供一个不错的高级概述: http://www.rubyinside.com/Why-rubyists-should-care-about-messaging-a-high-level-intro-5017.html
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
这通过工作示例给出了非常详细的解释: http://rubydoc.info/github/ruby-amqp/amqp/master/file/docs/Exchanges.textile#Publishing_messages_as_immediate_
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_
最后看看Bunny是否能够完成您需要为客户提供的所有服务,这很简单: https://github.com/celldee/bunny/wiki/Using-Bunny
Finally see if Bunny accomplishes everything you need for the client, it is simpler:https://github.com/celldee/bunny/wiki/Using-Bunny
希望有帮助
这篇关于Rails应用程序中的AMQP订户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!