LoginSignup
86

More than 5 years have passed since last update.

posted at

Organization

Railsでmemcacheを使ってobjectをキャッシュ

  • Page Cache
  • Action Cache
  • Fragment Cache

とかじゃなくて普通にObjectをStoreしたいんだよって時に。

Gemfile
gem 'dalli'
config/environments/production.rb
config.cache_store = :dalli_store

として以下のように使う。

Rails.cache.read("key")   # => nil
Rails.cache.write("key", [1,2,3], expires_in: 1.hour)  # 1時間で消える。
Rails.cache.read("key")   # => [1, 2, 3]

キーはシンボル(i.e. :key)にしてもOK

実際使うときは

hoge = Rails.cache.read("hoge_key")
if hoge.nil?
  hoge = get_hoge_value(xxx)
  Rails.cache.write("hoge_key", hoge, expires_in: 1.hour)
end

ってな感じになるはず。
これはfetchを使って、以下のようにも書ける。

hoge = Rails.cache.fetch("hoge_key", expires_in: 1.hour) do
  get_hoge_value(xxx)
end

基本はこっちしか使わないはず。

writeやfetchのオプションにcompress: trueを渡すとデータを圧縮してくれる。encode/decodeの時間はかかるだろうけど、通信量が削減されるので結果速くなることも。
実際、デフォルトで16Kの:compress_thresholdが設定されてるらしいので、元データが圧縮済みのデータじゃない限り、つけておけばいい気がする。

参照

http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html
http://guides.rubyonrails.org/caching_with_rails.html

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
What you can do with signing up
86