我通常通过加载 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://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_ 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 https://github.com/celldee/bunny/wiki/Using-Bunny
希望有帮助