LoginSignup
6
4

More than 3 years have passed since last update.

Rails の session store に Heroku Redis を利用する

Posted at

参考

1. Heroku CLI で アドオン を追加

heroku CLI で heroku-redis アドオンを追加する

$ heroku addons:create heroku-redis:hobby-dev 

Creating heroku-redis:hobby-dev on ⬢ xxxxx... free
Your add-on should be available in a few minutes.
! WARNING: Data stored in hobby plans on Heroku Redis are not persisted.
redis-xxxxx-xxxxx is being created in the background. The app will restart when complete...
Use heroku addons:info redis-xxxxx-xxxxx to check creation progress
Use heroku addons:docs heroku-redis to view documentation

heroku CLI で 環境変数 REDIS_URL (Redis のエンドポイント)が追加されてることを確認する

$ heroku config

=== shakestagram Config Vars
...
REDIS_URL: redis://xxxxx@xxxxx:xxxxx
...

2. Rails で session store の設定

Gemfileredis-rails を導入する

# Gemfile
gem 'redis-rails'

redis のエンドポイントを環境変数 REDIS_URL から取得するように設定する

# config/initializers/session_store.rb
if Rails.env.production?

  # Production では session_store に Redis を利用する
  Rails.application.config.session_store :redis_store, {
    servers: ENV['REDIS_URL'],
    expire_after: 1.week
  }

else
  # Production以外 では session_store に cookie_store(default) を利用する
  Rails.application.config.session_store :cookie_store, expire_after: 1.week

end
6
4
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
6
4