memcachedの使い方について簡単にメモします
動作環境は、Max OS X EI Captain 10.11.4, memcached 1.4.24 です。
memcachedのインストール
# http://qiita.com/makotok7/items/9998b15f79fc7a53af24 brew install memcached
localhostの11211ポートでmemcachedサーバを起動
$ memcached -p 11211 -d
詳しいオプションについては
- http://blog.nomadscafe.jp/2013/12/memcached-2.html
- http://gihyo.jp/dev/feature/01/memcached/0001?page=2
telnetでmemcachedサーバに接続
localhostの11211ポートでmemcachedサーバが動作しているとします。
$ telnet localhost 11211 Trying ::1... Connected to localhost. Escape character is '^]'.
memcachedサーバにデータを入れる
参考: https://www.tutorialspoint.com/memcached/memcached_set_data.htm http://l-w-i.net/t/memcached/command_001.txt
set [KVSのキー] [非圧縮/圧縮などのフラグ] [データの有効期限(秒). 0の場合は永続的に保存] [保存するデータのバイト数](return/enter) [KVSの値](return/enter) 123という3バイトの文字列をfooというキーに非圧縮で900秒保存させる set foo 0 900 3(return/enter) 123(return/enter) STORED
memcachedサーバにデータの取得と更新
参考: http://l-w-i.net/t/memcached/command_001.txt
get foo VALUE foo 0(非圧縮) 3(データ長:3バイト) 123 END gets foo VALUE foo 0(非圧縮) 3(データ長:3バイト) 2(cas ID) 123 END
getsで追加で表示されている最後の数字は、cas ID
といい、replace
コマンドでmemcached
上の同じキーに対する値を書き換えるたびに変化します。
replace foo 0 900 3 345 STORED gets foo VALUE foo 0 3 3 345 END
ユーザーAがmemcachedからデータを取得して処理したあとに保存しようとしたら、すでに他のユーザーBによって変更が加えられており、素直にユーザーAの計算結果を保存したらBの変更の履歴が消えてしまって困る、という場合があります。
それを避けるため、cas
コマンドを使って、データを取得した時のcas ID
をパラメータに与えて、「あの時からお変わりなかったら、変更したいんですけどー」という感じで変更コマンドを打ちます。
(ユーザーA) gets foo => VALUE foo 0 3 7 => 123 => END (ユーザーB) replace foo 0 0 3 abc => STORED ← 他のユーザーによりデータは更新されてcas IDは変化 (ユーザーA) cas foo 0 0 3 7 zzz => EXISTS 既に他のユーザがデータを書き換えたのでzzzは書き込めない
memcahcedサーバに入っているデータの状態について調べる
参考: http://taka512.hatenablog.com/entry/20100324/1269428213
stats STAT pid 8365 STAT uptime 2670 起動時間 STAT time 1476973152 STAT version 1.4.24 STAT libevent 2.0.22-stable STAT pointer_size 64 OSが32bit又は64bit STAT rusage_user 0.037374 プロセスがユーザモードで動作した累計時間?(秒.マイクロ秒) STAT rusage_system 0.061396 プロセスがカーネルモードで動作した累計時間?(秒.マイクロ秒) STAT curr_connections 10 現在のデータ数 STAT total_connections 11 STAT connection_structures 11 memcacheが確保したコネクション構造体数 STAT reserved_fds 20 STAT cmd_get 6 GETコマンド発行の累計 STAT cmd_set 7 SETコマンド発行の累計 STAT cmd_flush 0 STAT cmd_touch 0 STAT get_hits 5 リクエストでキーが見つかった数 STAT get_misses 1 リクエストでキーが見つからなかった数 STAT delete_misses 0 STAT delete_hits 0 STAT incr_misses 0 STAT incr_hits 0 STAT decr_misses 0 STAT decr_hits 0 STAT cas_misses 0 STAT cas_hits 0 STAT cas_badval 1 STAT touch_hits 0 STAT touch_misses 0 STAT auth_cmds 0 STAT auth_errors 0 STAT bytes_read 284 ネットワークから受信したバイト数 STAT bytes_written 292 ネットワークへ送信したバイト数 STAT limit_maxbytes 67108864 memcacheの最大容量(バイト) STAT accepting_conns 1 STAT listen_disabled_num 0 STAT threads 4 STAT conn_yields 0 STAT hash_power_level 16 STAT hash_bytes 524288 STAT hash_is_expanding 0 STAT malloc_fails 0 STAT bytes 71 STAT curr_items 1 STAT total_items 3 STAT expired_unfetched 1 STAT evicted_unfetched 0 STAT evictions 0 STAT reclaimed 1 STAT crawler_reclaimed 0 STAT crawler_items_checked 0 STAT lrutail_reflocked 0 END