Rails 6 个活动作业。为什么我不能发送异步任务?

Rails 6 Active Job. Why I can't send async tasks?

我正在遵循 https://guides.rubyonrails.org/action_mailer_basics.html#calling-the-mailer

上的 Action Mailer 指南

我做了几乎和教程展示的一样。控制器:

def create
  @user = User.create(user_params)

  if @user && UserMailer.with(user: @user).welcome_email.deliver_later
     token = encode_token({ user_id: @user.id })
     render json: { token: token }, status: :created
  else
     render json: @user.errors.messages, status: :bad_request
  end
end

邮递员:

class UserMailer < ApplicationMailer
  default from: 'notifications@example.com'

  def welcome_email
    @user = params[:user]
    @url  = 'http://example.com/login'
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
  end
end

但是当我发出请求时,Active Job 大喊:

ActiveJob::SerializationError => "Unsupported argument type: User"

使用 deliver_now

可以正常工作

这表明我们的 :async 适配器有问题。但正如指南所说:

Active Job's default behavior is to execute jobs via the :async adapter. So, you can use deliver_later to send emails asynchronously. Active Job's default adapter runs jobs with an in-process thread pool. It's well-suited for the development/test environments, since it doesn't require any external infrastructure, but it's a poor fit for production since it drops pending jobs on restart. If you need a persistent backend, you will need to use an Active Job adapter that has a persistent backend (Sidekiq, Resque, etc).

那么我在这里缺少什么?

它不起作用,因为 ActiveJob 不支持这些对象。要使其可访问,您必须将其转换为 json 字符串,然后在邮件程序方法中反序列化。

尝试将对象作为 json 字符串发送并检索 id 值,然后使用:

@user = User.find(params[:user_id])

另一种方法是使用 Resque 或 Sidekiq 来处理这些作业。它们真的很方便。

帮助人们摆脱困境的另一个来源:

如果您想跟随 rails 指南了解更多信息:

https://guides.rubyonrails.org/active_job_basics.html#globalid