MENU

rails6にredisを導入してheroku上でも動かす

rails側の設定

gemの導入

gem 'redis-objects'
gem 'redis-rails'

config/initializers/redis.rbを作成し以下を書く

Redis.current = Redis.new

redisを使うクラスでredisオブジェクトを作る

例えばこんなの。

class Sample
  include Redis::Objects
  counter :total_count
  def id
    1
  end
end

redisオブジェクトに値を入れる処理を作る

例えばこんなの。

@mathos = Mathos.new
@mathos.total_mathos.increment

ローカル環境での設定

config/environments/development.rbに以下を書く

config.cache_store = :redis_store, 'redis://localhost:6379/0/cache'

herokuでの設定

config/environments/production.rbに以下を書く
なお、heroku上はenviromentがproductionの想定

config.cache_store = :redis_store, ENV["REDIS_URL"]

herokuの管理画面からheroku redisをインストール

f:id:spreadthec0ntents:20210620184803p:plain

サンプル

ボタンを押すとカウンターの値を増やせるアプリ

living-for-ever.herokuapp.com