Rails3を使っていて、memcachedを利用できるようにしたときのメモです。
memcachedを使えるようにconfigを設定する
ローカル環境がすべてキャッシュを使うようになると不便なため、自分はdev_with_cachingという環境を作成しました。productionの場合もほぼ同じやり方でできるため省きます。
config/database.ymlに以下を追記。database.ymlは自分の環境に合わせてください。
dev_with_caching: adapter: mysql encoding: utf8 reconnect: false database: myapp_development pool: 5 username: root password: socket: /opt/local/var/run/mysql5/mysqld.sock
config/environments/dev_with_caching.rbというファイルに以下の内容を書き込み。ポイントとしてはconfig.cache_classesをtrueに、config.action_controller.perform_cachingをtrueに、config_cache_storeに適切な設定をする事です。またproductionのキャッシュを汚さないようにnamespaceを決めておくのも必要です。
MyApp::Application.configure do # Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = true config.cache_store = :mem_cache_store, 'localhost', { :namespace => 'myapp_dev_with_caching'} # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin end
キャッシュを使う
上の設定をすると、Rails.cacheでmemcachedのためのクライアントオブジェクトを取得できるようになります。例えば以下のようなメソッドを使う事が出来ます。詳細はrailsのドキュメントを参照してください。
Rails.cache.write('test', 'test') # testをキーとして、testという値をキャッシュ Rails.cache.read('test') # キーがtestの値を取得 Rails.cache.delete('test') # キーがtestのキャッシュを削除 Rails.cache.write('time_expire', '5秒後に消える', expires_in => 5.seconds) Rails.cache.read('time_expire') # => '5秒後に消える' sleep(5) Rails.cache.read('time_expire') # => nil # もちろんオブジェクトもキャッシュ可能 Rails.cache.write('hash', {'hoge' => 'piyo', 'foo' => 'buz'}) Rails.cache.read('hash') # => {'hoge' => 'piyo', 'foo' => 'buz'} Rails.cache.clear # すべてのキャッシュをクリア
このように非常に便利にキャッシュを使う事が出来ます。時間でキャッシュを管理したり、オブジェクトは自動でシリアライズしてくれたりするので便利ですね。