Rails3 で Session を Memcache に入れる
Rails3 で Session を Memcache に入れるための手順です。
まずは、memcache-client をインストールするために Gemfile に下記の行を追加します。
gem 'memcache-client'
次に bundle install を実行して memcache-client をインストールします。
$ sudo bundle install Fetching source index for http://rubygems.org/ : Installing memcache-client (1.8.5) : Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
デフォルトでは Session は Cookie に保存するようになっているので、config/initializers/session_store.rb を下記のように修正して Memcache に Session を保存するように修正します。
(memcache_server にて指定している Memcache サーバは、開発環境・本番環境と切り替えたほうが良いと思いますので、config/environments/development.rb 等に適宜逃がしてください。)
Project::Application.config.session_store :mem_cache_store Project::Application.config.session_options = { :cookie_only => false, :key => '_session', :memcache_server => 'localhost:11211' }
これで Session は Memcache に保存されるようになります。
ですが、Session ID はまだ Cookie 上に保存されます。
これを URL パラメータとして引き回す場合は jpmobile を使用します。
これも memcache-client と同様に Gemfile に jpmobile の設定を追加して bundle install を実行します。
gem 'memcache-client' gem 'jpmobile'
$ sudo bundle install Fetching source index for http://rubygems.org/ : Using memcache-client (1.8.5) Installing jpmobile (0.1.2) : Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
あとは app/controllers/application_controller.rb に trans_sid :always を追記すれば Cookie を使用しないで Session を Memcache に保存できます。
class ApplicationController < ActionController::Base trans_sid :always protect_from_forgery end