LoginSignup
15
19

More than 5 years have passed since last update.

Resqueメモ

Last updated at Posted at 2015-02-21

Ruby on Railsで使うResqueの自分用メモ。

Resqueについて

Redisを利用してバックグラウンドなjobを実行するためのライブラリ。

基礎

  • workerという概念がある(jobとも言う)
    • 名称が複数あるとややこしいのでjobとする
  • jobを一つの単位として非同期に実行できる

流れ

  • jobクラスにqueue名を設定
  • Resqueのqueueに対してjobクラスを積む
  • 動作させたいqueueを名前指定して実行
    • queueに積まれているjobが順次実行される

前提

すでにrailsアプリケーションをインストール済みであることを前提としている。

  • ruby 2.2.0
  • Rails 4.2.0

導入

redisのインストール

$ brew install redis

redisのserverを起動

$ redis-server

Gemfile

Gemfile
gem "resque"
$ bundle install

resqueは1.25.2がインストールされた。

job作成

rakeファイルを作成

rakeについてはRails で Rake タスク作成と rake コマンド実行の色々な方法を見るとよく分かる。

rails generatorでresqueなtaskを生成。

$ bundle exec rails g task resque

lib/tasks/resque.rakeが作られるので確認

lib/tasks/resque.rake
namespace :resque do
end

これにrequire 'resque/tasks' を追記

lib/tasks/resque.rake
require 'resque/tasks'
namespace :resque do
end

手順としてrails gを使ったが、結局上記のようなコードになればいい。

job

app/workers/以下にmylogger.rbを置く

class Mylogger
  @queue = :default # queue名を指定

  def self.perform(name)
    path = File.expand_path("log/users.log", Rails.root)
    File.open(path, 'a') do |f|
      f.puts "User: #{name}"
    end
  end

end
  • queue名を指定
  • クラスメソッドperformに実行したい処理を実装する

このクラス名はjobをキューに積む際に重要

jobをキューに積む

job用に作ったMyloggerクラスを指定することでキューに積む。Webの画面から実行すると分かりやすいのでHomeControllerのように適当なControllerのメソッドを利用する

class HomeController < ApplicationController
  def show
    Resque.enqueue(Mylogger, params[:name])
    render :text => params[:name]
  end
end

これは下記のようなURLにアクセスすることで、"User: abc"と表示させたいだけ
http://0.0.0.0:3000/home/show?name=abc

実行

queueの実行

jobのqueue名を指定

$ QUEUE=default rake environment resque:work
  • 根本的には rake resque:work をしたい
    • resque:workでresque.rakeを呼び出す決まりと思っておく
  • environmentを呼ぶことでタスクに:environmentの引数を渡す
    • environmentを使うことでModelにアクセスできる
    • resque.rake側にenvironmentを記載してもよいがしなかったので引数として渡している

確認

ログファイルを確認

$ tail -f log/users.log

resqueの管理画面

route.rbに以下のように追記

mount Resque::Server.new, at: "/resque"

管理画面にアクセスする
http://localhost:3000/resque

  • Queuesに積まれているキューの数と引数を表示

その他

namespaceを環境によって分ける

同一のサーバー上で複数アプリがある場合などに必要なのかも

参考URL

15
19
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
15
19