Railsのセッション管理にmemcachedを使う
▼ 参照サイト
・HowtoChangeSessionStore
・dreammindの日記
・夜のDiscovery
・くりまるwebつくる
==[RAILS_ROOT/config/environment.rb]==== ... SESSION_CACHE = MemCache.new(['192.168.0.1:11211'], {:namespace => 'rails'}) ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.merge!({'cache' => SESSION_CACHE}) ...
どの記事も恐らくはHowtoChangeSessionStoreを参考にされていると思われ、やり方はほぼ等しいようだが、なんで設定ファイルでコネクションをnewしないといけないのか、他に設定方法はないのかなぁと思う。
というわけでMemCacheの拡張プラグインを作ってみた。これを導入することで以下のようにmemcachedの設定をすることができる。
==[RAILS_ROOT/config/environment.rb]==== Rails::Initializer.run do |config| ... config.action_controller.session_store = :mem_cache_store end ==[RAILS_ROOT/config/memcached.yml]==== session: expires: '6h' options: multithread: false namespace: 'rubricks' readonly: false servers: ['localhost:11211']
これだけじゃ寂しいので、運用時にmemcachedの動作状況を確認するためのユーティリティもつけてみた。実際に使う際はコンソールじゃなくて、Rubyスクリプトにして適当なファイルにリダイレクトしないと大変なことになるかも。
# ruby script/console Loading development environment. >> MemCacheUtil.dump(:status) [127.0.0.1:11211] pid 3230 uptime 167095 time 1215991229 version 1.2.5 pointer_size 32 rusage_user 0.100000 rusage_system 0.320000 curr_items 19 total_items 63 bytes 3545 curr_connections 6 total_connections 35 connection_structures 18 cmd_get 73 cmd_set 63 get_hits 45 get_misses 28 evictions 0 bytes_read 18951 bytes_written 60749 limit_maxbytes 67108864 threads 1 replication MASTER repcached_version 2.0 repcached_qi_free 8192 => nil >> MemCacheUtil.dump(:slabs) [127.0.0.1:11211] id chunk_size max_age total_pages count full -------------------------------------------------------------- 2 112bytes sec 1 no 5 232bytes 2sec 1 1 no -------------------------------------------------------------- => nil >> MemCacheUtil.dump(:items) [127.0.0.1:11211] name_space key size ------------------------------------------------------------------------------- test session:daceb6b0299fb8df5226537e7042b11e 103bytes ------------------------------------------------------------------------------- => nil