Railsでキャッシュしてみる
RailsでHello, world!を表示してみる
の続き
Railsでキャッシュしてみる。
ファイルキャッシュ
サンプルのコントローラを下記のように修正する。
$ vi app/controllers/sample_controller.rb
class SampleController < ApplicationController def index count = Rails.cache.read(:count) count = 0 if count.nil? count += 1 Rails.cache.write(:count, count, expires_in: 1.hour) render :text => count end end
ブラウザからアクセスすると最初に「1」と表示され、
アクセスするたびにカウントされていく。
キャッシュは、tmp/cache/のディレクトリに作られる。
$ tree tmp/ tmp/ └── cache └── 22A └── 5F0 └── count
下記のコマンドでキャッシュをクリアできる。
$ rake tmp:cache:clear
$ tree tmp/ tmp/ └── cache
(失敗)Memcache
Memcacheにキャッシュを保存してみる。
まず、Memcacheをインストールしておく。
$ sudo yum -y install memcached $ sudo chkconfig memcached on $ sudo service memcached start
memcacheのgemを入れ、
$ vi Gemfile gem 'memcache-client' ←追加
$ bundle install
memcacheを使うよう設定する。
$ vi config/environments/development.rb
config.cache_store = :mem_cache_store ←追加
再起動して設定を反映。
$ sudo service httpd restart
しかし、アクセスしてみると、エラーが出る。
よく分からない。
Could not find cache store adapter for mem_cache_store (cannot load such file -- dalli) (RuntimeError)