xps*_*15z 13 ruby-on-rails heroku redis
我在Heroku上使用自定义域名,我有Redis附加组件.我需要帮助了解如何为电子邮件通知创建后台工作程序.用户可以互相收件箱,我希望向用户发送收到的每封新邮件的电子邮件通知.我有开发工作的通知,但我不擅长创建Heroku所需的后台作业,否则服务器会超时.
消息控制器:
def create
@recipient = User.find(params[:user])
current_user.send_message(@recipient, params[:body], params[:subject])
flash[:notice] = "Message has been sent!"
if request.xhr?
render :json => {:notice => flash[:notice]}
else
redirect_to :conversations
end
end
Run Code Online (Sandbox Code Playgroud)
用户模型:
def mailboxer_email(object)
if self.no_email
email
else
nil
end
end
Run Code Online (Sandbox Code Playgroud)
Mailboxer.rb:
Mailboxer.setup do |config|
#Configures if you applications uses or no the email sending for Notifications and Messages
config.uses_emails = false
#Configures the default from for the email sent for Messages and Notifications of Mailboxer
config.default_from = "no-reply@domain.com"
#Configures the methods needed by mailboxer
config.email_method = :mailboxer_email
config.name_method = :name
#Configures if you use or not a search engine and wich one are you using
#Supported enignes: [:solr,:sphinx]
config.search_enabled = false
config.search_engine = :sphinx
end
Run Code Online (Sandbox Code Playgroud)
Sidekiq绝对是Heroku的方式.我认为邮箱不支持开箱即用的后台配置.值得庆幸的是,使用sidekiq的排队过程仍然非常容易.
gem 'sidekiq'到您的gemfile并运行bundle.app/workers/message_worker.rb.class MessageWorker
include Sidekiq::Worker
def perform(sender_id, recipient_id, body, subject)
sender = User.find(sender_id)
recipient = User.find(recipient_id)
sender.send_message(recipient, body, subject)
end
end
Run Code Online (Sandbox Code Playgroud)
去掉: current_user.send_message(@recipient, params[:body], params[:subject])
加: MessageWorker.perform_async(current_user.id, @recipient.id, params[:body], params[:subject])
注意:您永远不应该传递工作者ActiveRecord对象.这就是为什么我设置这个方法来传递用户ID并在worker的perform方法中查找它们,而不是整个对象.
最后,重启服务器并运行bundle exec sidekiq.现在您的应用应该发送电子邮件背景.
部署时,您需要为工作人员单独设置一个dyno,如下所示:worker: bundle exec sidekiq.您还需要Heroku的redis插件.
听起来像H21请求超时:
HTTP请求需要超过30秒才能完成.
要在RoR中为此创建后台工作程序,您应该获取Resque,这是一个Redis支持的RoR背景排队库.这是一个演示.另一个演示.另一个演示.
要了解有关在Heroku中使用Resque的更多信息,您还可以在此处阅读herokue文章.或者本教程(虽然它是旧的).另一位伟大的教程.
还有一个resque_mailer gem可以为你加速.
gem install resque_mailer #or add it to your Gemfile & use bundler
Run Code Online (Sandbox Code Playgroud)
这很简单.以下是作者的工作演示片段:
class Notifier < ActionMailer::Base
include Resque::Mailer
default :from => "from@example.com"
def test(data={})
data.symbolize_keys!
Rails.logger.info "sending test mail"
Rails.logger.info "params: #{data.keys.join(',')}"
Rails.logger.info ""
@subject = data[:subject] || "Testing mail"
mail(:to => "nap@localhost.local",
:subject => @subject)
end
end
Run Code Online (Sandbox Code Playgroud)
做Notifier.test.deliver将传递邮件.
您还可以考虑使用SES等邮件传递服务.
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |