Stan Blog

學習過程中的一些記錄

[Rails] 使用 memcached 儲存 session

memcached 是一套 Name-Value Pair (NVP) 分散式記憶體快取系統, Key 的長度被限制在 250 characters, 儲存的資料不能超過 1 megabyte

要特別注意, memcached 不是 persistent data store, 只要關掉 memcahed 重開, 裡面的資料會通通不見

Rails 專案

Gemfile 內加上

gem 'dalli'

執行 bundle install

接著將 config/enviroment/production.rb 加上

config.cache_store = :dalli_store

config/initializers/session_store.rb 改為

Rails.application.config.session_store ActionDispatch::Session::CacheStore, expire_after: 20.minutes

p.s 本地端測試要將 config/enviroment/development.rb 內的設定改為如下

config.action_controller.perform_caching = true
config.cache_store = :dalli_store

本地端

這邊使用 Homebrew 安裝

$ brew install memcached

使用 telnet 連上 memcached

$ telnet 127.0.0.1 11211

# 查看目前 memcached 的資訊
stats

2019-03-02 21 45 21

# 查看 memcached 的所有 key (0 是全部)
stats items

2019-03-02 21 45 38

# 查看 slab id 的 key (arg1 是 STAT items: 後面的 slab id, arg2 是要列出的 key 的數量)
stats cachedump arg1 arg2

2019-03-02 21 45 53

# 查看 key 的 value 值
get {key_name}

2019-03-02 21 48 16

主機端

$ apt-get install memcached


Ref:

Comments

comments powered by Disqus