0
0

パーフェクトRubyonRails備忘録5

Posted at

ActiveJobによる非同期実行

  • どういう時に使う?

    • リクエストからレスポンスまで時間がかかりそうな時などに、レスポンスだけ返して処理は非同期で実行する
  • ジョブの実装

    • ジョブクラスの生成
    rails g job async_log
    
    • app/jobs/async_log_job.rb ファイルとテストファイルが作られる
    • ジョブクラスの実装
    class AsyncLogJob < ApplicationJob
      queue_as :default
      
      def perform(message: "hello")
        AsyncLog.create!(message: message) # 実行したい処理を書く
      end
    end
    
    • ジョブをキューに入れる
      • ジョブの実行はバックエンドが担当する(ややこしや)
      • デフォルトのバックエンドは async
      • 追加方法
        • AsyncLogJob.perform_later
        • バックエンドキューにジョブを追加し、非同期実行している
      • 実行タイミングの指定もできる
        • AsyncLogJob.set(wait: 1.minute).perform_later
        • 1分後にバックエンドキューに追加される
        • wait_untilで実行日時の指定もできる
  • ジョブへ渡す引数には制限がある

    • 利用できるオブジェクトの代表例
      • 基本型(Nil, String, Integer, Float, BigDecimal, True, False)
      • Symbol
      • 日時を扱う型
      • Hash
      • Array
      • ActiveRecord
  • 複数キューの管理

    • queue_as :defaultとなっている部分を queue_as :async_logなどに変更することでジョブごとにキューを扱える
    • バックエンドがsidekiqの場合、 sidekiq.ymlファイルに追加したいキューを追加し、sidekiqプロセスを再起動する必要がある
    # config/sidekiq.yml
    :queues:
      - default
      - aysnc_log
    
  • ジョブの例外処理

    • ジョブのリトライ
    class AsyncLogJob < ApplicationJob
      # 略
      retry_on StandardError, wait: 1.minute, attempts: 3
      # StandardErrorになったら1分待って、3回まで再実行する
      # 例外は複数指定可能
    
    • ジョブの破棄
    class AsyncLogJob < ApplicationJob
      # 略
      discard_on StarndardError
      # StandardErrorになったらジョブを破棄する
    
  • 詳細は以下

    Active Job の基礎 - Railsガイド

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0