QueuedMail
- Author
-
Yuichi Takeuchi [email protected]
- Website
- Copyright
-
Copyright 2012 Yuichi Takeuchi
- License
-
MIT-LICENSE.
何が嬉しいの?
時間のかかるメール送信処理をバックグラウンドで処理することで、ユーザーに素早いレスポンスを返すことができます。
ActionMailer::Base#deliverでを実際のメール送信ではなくジョブキューへの登録を行うようになります。 特徴はActionMailerの設定を変更するだけよく、アプリケーションコードへの変更が不要なことです。 このため、とても簡単に導入することができます。
なおジョブキューは、選べる2タイプ。
-
Amazon SQS (要 aws-sdk gem)
-
Resque (要 resque gem & Redis)
環境
-
Ruby 1.9.3 or later
-
Ruby on Rails 3.2.8 or later
-
mail 2.4.4 or later
インストール
Gemfile
gem 'queued_mail', '~> 0.2.6'
bundle install
マイグレーション。
rake queued_mail:install:migrations
rake db:migrate
設定変更。mail_queue_outbound_delivery_method には :test 含め、delivery_methodに指定可能なものならなんでも大丈夫、のはず。
# in config/environments/production.rb (or other environment)
config.action_mailer.delivery_method = :queued
config.mail_queue_service = :resque # or :amazon_sqs
config.mail_queue_name = :mail_queue
config.mail_queue_outbound_delivery_method = :smtp # default: :sendmail
config.action_mailer.smtp_settings = {
address: "smtp.sendgrid.net",
port: 25,
domain: "site.com",
user_name: "[email protected]",
password: "smtp-password"
}
ワーカー起動
PIDFILE=/tmp/queued_mail.pid rake environment queued_mail:work
もちろんPIDFILEは省略できます。
またはResqueであれば以下のようにもできます。
QUEUE=mail_queue rake environment resque:work
実運用では適当にdaemon化すればよいと思います。
キューの設定
高速性優先のResqueと手軽さ優先のSQSが選択できます。
Resqueを使う(デフォルト)
(1) Redisサーバーを準備する
(2) Railsでresqueを使用する設定を行う
(3) config/application.rb等でキューとしてResqueを使うことを設定する(省略可能)
config.mail_queue_service = :resque
Amazon SQSを使う
(1) AWS ManagementConsoleなどでキューを作成
(2) Railsでaws-sdkを使用する設定を行う(config/aws.yml など。必要に応じてsqs_endpoint も設定する。)
(3) config/application.rb等でキューとしてAmazonSQSを使うことを設定する
config.mail_queue_service = :amazon_sqs
config.mail_queue_name = '1で作成したキューの名前'
メール取りだしのリトライ設定
DBのコミット前にキューを取得してしまった場合など、ジョブ実行の段階でメッセージを取得できない可能性に対処するため、指定回数までメールの取得を試みるようにしました。
config.mail_queue_retry_limit = 3 # 3回まで再試行する(最初の1回+再試行3回)
config.mail_queue_retry_interval = 5 # 5秒後に再試行
TODO
-
Workerとかめんどくさい人用 cronで叩けるコントローラ
-
テスト
0.1系からのアップグレード
queued_mail_messagesテーブルの構造が変わってます。
rake queued_mail:install:migrations でマイグレーションファイルをコピーして開き、便宜移行コードに変更してください。
注意
-
仕様変更があっても泣かない。
-
バグっても泣かない。
-
何が起きても責任はとれません。