ruby-on-rails - 发送电子邮件时 Heroku 超时

标签 ruby-on-rails heroku redis

我在 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 的排队过程仍然非常简单。

  1. gem 'sidekiq' 添加到您的 gemfile 并运行 bundle
  2. 创建工作文件 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
  1. 更新您的 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 方法中查找它们,而不是在整个对象中查找。

  1. 最后,重新启动服务器并运行 bundle exec sidekiq。现在您的应用程序应该发送电子邮件背景。

  2. 当您部署时,您将需要一个单独的 dyno 用于 worker,它应该如下所示:worker: bundle exec sidekiq。您还需要 Heroku 的 redis 附加组件。

关于ruby-on-rails - 发送电子邮件时 Heroku 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318439/

相关文章:

ruby-on-rails - RSPEC NoMethodError : helper method calling another controller's action -

ruby-on-rails - View 中带有空格的 Rails 字符串

ruby-on-rails - 如何在用户未登录时将用户重定向到登录页面

ruby-on-rails - Heroku 本地 byebug/调试器损坏

java - 如何用真实数据库表填充 h2 内存表?

jquery - Bootstrap CSS - 缩略图图像调整大小和响应式

Node.JS、Express 和 Heroku - 如何处理 HTTP 和 HTTPS?

php - 无法在 Heroku 上迁移数据库(试过 MySQL 和 PostgreSQL)

azure - session 超时在 Azure Redis 缓存 session 状态提供程序中不会滑动

php - 如何使用 redis 库在 codeigniter 中通过 sessionid 更改 session 数据?