异步执行在当前(这个东西在rails的领域,变化的可能很大,总是有更好用的插件,更酷的想法冒出来)
最流行的应该就是delayed_job,这个的资料比较多,例如,railscast就有介绍。所以,老猪这里就简单说说用法。delayed_job异步思路还是,在需要调用的地方加delay,例外启动一个deamon,处理任务。
其中,railscast的介绍已经被JE某XD翻译了,用到的参考http://enn.javaeye.com/blog/632960
原本地址:
http://asciicasts.com/episodes/171-delayed-job
并该方案当前的Rails 3解决方案JE也有
参考如下:
http://t0uch.javaeye.com/blog/673336
安装:
script/plugin install git://github.com/collectiveidea/delayed_job.git
生成:
script/generate delayed_job
rake db:migrate
#后台处理
rake jobs:work
生成表如下:
create_table :delayed_jobs, :force => true do |table|
table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
table.text :handler # YAML-encoded string of the object that will do work
table.string :last_error # reason for last failure (See Note below)
table.datetime :run_at # When to run. Could be Time.now for immediately, or sometime in the future.
table.datetime :locked_at # Set when a client is working on this object
table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
table.string :locked_by # Who is working on this object (if locked)
table.timestamps
end
另一个知名的解决方案是ar_mailer
ar_mailer的时间要长,用起来和delayed job的解决方案差不多,异步的思路把任务存到数据库,然后,后台任务轮询触发。
和Delayed Job相同,也有一篇介绍Rails 3使用的在letrails上
http://www.letrails.cn/archives/ar_mailer-rails-3-plugi
老猪自己当前的项目用的ar_mailer
大致使用如下:
$ sudo gem install adzap-ar_mailer
config.gem "adzap-ar_mailer"
./script/generate ar_mailer
#config/environments/production.rb
config.action_mailer.delivery_method = :activerecord
启动后台
$ ar_sendmail
最后,测试异步的发送邮件
也是使用一个插件,保证在测试环境邮件并不真正发送,就可以验证了
#$ ./script/plugin install git://github.com/ngty/action_mailer_cache_delivery.git
#RAILS_ROOT/config/environments/test.rb,
config.action_mailer.delivery_method = :cache