我在 Heroku 上有一个自定义域,我有 Redis 附加组件。我需要帮助了解如何为电子邮件通知创建后台工作人员。用户可以在收件箱中互相发送消息,我想为收到的每条新消息向用户发送电子邮件通知。我有通知在开发中工作,但我不擅长创建 Heroku 所需的后台作业,否则服务器会超时。
消息 Controller :
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
用户模型:
def mailboxer_email(object)
if self.no_email
email
else
nil
end
end
邮箱.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 which one are you using
#Supported enignes: [:solr,:sphinx]
config.search_enabled = false
config.search_engine = :sphinx
end
最佳答案
Sidekiq 绝对是与 Heroku 搭配使用的方式。我认为 mailboxer 不支持开箱即用的后台配置。值得庆幸的是,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
- 更新您的 Controller 以将 Worker 排队
删除:current_user.send_message(@recipient, params[:body], params[:subject])
添加:MessageWorker.perform_async(current_user.id, @recipient.id, params[:body], params[:subject])
注意:永远不要传递 worker ActiveRecord 对象。这就是为什么我设置此方法以传递用户 ID 并在工作人员的 perform
方法中查找它们,而不是在整个对象中查找。
最后,重新启动服务器并运行
bundle exec sidekiq
。现在您的应用程序应该发送电子邮件背景。当您部署时,您将需要一个单独的 dyno 用于 worker,它应该如下所示:
worker: bundle exec sidekiq
。您还需要 Heroku 的 redis 附加组件。
关于ruby-on-rails - 发送电子邮件时 Heroku 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318439/