memcachedについて
公式ページ:http://memcached.org/
参考:http://gihyo.jp/dev/feature/01/memcached/0001
特徴
- メモリが不足すると最も使用されていないキャッシュから削除される
用語
オブジェクト / アイテム
memcachedで扱うデータのこと
slab
slabはmemcachedがオブジェクトを保存するために予め確保しておく領域のこと。
slab内でchunkという領域に分割され、キャッシュはchunk内に保存される。
chunkのサイズは各slabで異なり、オブジェクトを保存する際、そのオブジェクトサイズより大きく、かつ最も最小のslab内で保存される。
CAS
キャッシュの一貫性を確保するための機能。
CASを使用するクライアントはデータ更新前に一度データのCAS値を取得し、
更新時にそのCAS値を一緒に送信する。
memcachedはCAS値が一致すれば更新を行う。
このCASを実現するために各オブジェクトには8byteのCAS値が与えられる。
環境
- OS
CentOS release 6.4 (64bit)
- Memcached Version
1.4.17
サーバの構築
NTP
時刻調整のためにNTPをインストールする。
インストール
yum install ntp
- log
[root@mysql1 ~]# yum install ntp Loaded plugins: fastestmirror base | 3.7 kB 00:00 base/primary_db | 3.5 MB 00:00 extras | 3.4 kB 00:00 extras/primary_db | 18 kB 00:00 updates | 3.4 kB 00:00 updates/primary_db | 765 kB 00:01 Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package ntp.i686 0:4.2.6p5-1.el6.centos will be installed --> Processing Dependency: ntpdate = 4.2.6p5-1.el6.centos for package: ntp-4.2.6p5-1.el6.centos.i686 --> Processing Dependency: libcrypto.so.10(libcrypto.so.10) for package: ntp-4.2.6p5-1.el6.centos.i686 --> Processing Dependency: libcrypto.so.10(OPENSSL_1.0.1) for package: ntp-4.2.6p5-1.el6.centos.i686 --> Running transaction check ---> Package ntpdate.i686 0:4.2.6p5-1.el6.centos will be installed ---> Package openssl.i686 0:1.0.0-27.el6 will be updated ---> Package openssl.i686 0:1.0.1e-16.el6_5.1 will be an update --> Processing Dependency: make for package: openssl-1.0.1e-16.el6_5.1.i686 --> Running transaction check ---> Package make.i686 1:3.81-20.el6 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: ntp i686 4.2.6p5-1.el6.centos base 586 k Installing for dependencies: make i686 1:3.81-20.el6 base 386 k ntpdate i686 4.2.6p5-1.el6.centos base 74 k Updating for dependencies: openssl i686 1.0.1e-16.el6_5.1 updates 1.5 M Transaction Summary ================================================================================ Install 3 Package(s) Upgrade 1 Package(s) Total download size: 2.5 M Is this ok [y/N]: y Downloading Packages: (1/4): make-3.81-20.el6.i686.rpm | 386 kB 00:00 (2/4): ntp-4.2.6p5-1.el6.centos.i686.rpm | 586 kB 00:00 (3/4): ntpdate-4.2.6p5-1.el6.centos.i686.rpm | 74 kB 00:00 (4/4): openssl-1.0.1e-16.el6_5.1.i686.rpm | 1.5 MB 00:04 -------------------------------------------------------------------------------- Total 520 kB/s | 2.5 MB 00:04 warning: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 Importing GPG key 0xC105B9DE: Userid : CentOS-6 Key (CentOS 6 Official Signing Key) <centos-6-key@centos.org> Package: centos-release-6-4.el6.centos.10.i686 (@anaconda-CentOS-201303020136.i386/6.4) From : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 Is this ok [y/N]: y Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Installing : 1:make-3.81-20.el6.i686 1/5 Updating : openssl-1.0.1e-16.el6_5.1.i686 2/5 Installing : ntpdate-4.2.6p5-1.el6.centos.i686 3/5 Installing : ntp-4.2.6p5-1.el6.centos.i686 4/5 Cleanup : openssl-1.0.0-27.el6.i686 5/5 Verifying : openssl-1.0.1e-16.el6_5.1.i686 1/5 Verifying : ntp-4.2.6p5-1.el6.centos.i686 2/5 Verifying : 1:make-3.81-20.el6.i686 3/5 Verifying : ntpdate-4.2.6p5-1.el6.centos.i686 4/5 Verifying : openssl-1.0.0-27.el6.i686 5/5 Installed: ntp.i686 0:4.2.6p5-1.el6.centos Dependency Installed: make.i686 1:3.81-20.el6 ntpdate.i686 0:4.2.6p5-1.el6.centos Dependency Updated: openssl.i686 0:1.0.1e-16.el6_5.1 Complete!
NTPの設定
ここでは仮に公開ntpサーバを利用する設定を以下のように行う。
独立行政法人情報通信研究機構 (NICT)のNTPサーバ:ntp.nict.jp と
インターネットマルチフィードのNTPサーバ:ntp.jst.mfeed.ad.jpの2つを設定する。
vi /etc/ntp.conf
- 変更内容
初期状態の「*.centos.pool.ntp.org」をコメントアウトし、
#server 0.centos.pool.ntp.org #server 1.centos.pool.ntp.org #server 2.centos.pool.ntp.org server ntp.nict.jp minpoll 6 maxpoll 6 server ntp.jst.mfeed.ad.jp minpoll 6 maxpoll 6 tinker panic 0
ここで、「minpoll 6 maxpoll 6」とは同期タイミングの設定で、2^6秒、つまり64秒ごとに同期を行う。
更にデフォルトではNTPサーバとクライアントの時刻差が1000秒以上あると正常に同期できないので、
その差を無視するよう設定する。
常に起動し続ける本番環境であれば、これらは不要である。
ntpサービス起動
ntpサービスは停止しているので、起動させる。
service ntpd start
更にntpdサービスをOS起動時に起動するように設定する。
- 現在の設定
[root@mysql1 ~]# chkconfig --list ntpd ntpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
- Level3で有効化
chkconfig --level 3 ntpd on
- 結果
[root@mysql1 ~]# chkconfig --list ntpd ntpd 0:off 1:off 2:off 3:on 4:off 5:off 6:off
時刻確認
dateコマンドで現在時刻が正しく同期されているかを確認する。
Memcachedの構築
Memcachedのインストール
ソースコードからインストール
ソースコードからインストールすることで、インストール先を変更したり、
不要な機能を削除したりさまざまなオプションを指定できる。
- rootになる
su -
- memcachedユーザを作成する
useradd --user-group --no-create-home --shell /sbin/nologin memcached
- 関連パッケージをインストールする
- コンパイラをインストールする
yum install gcc -y
- memcachedで使用するlibeventパッケージをインストールする
yum install libevent -y yum install libevent-devel -y # 一括インストールの場合 yum install gcc libevent libevent-devel -y
- コンパイラをインストールする
- scpやwgetを使用してソースコードをダウンロードする
wget http://www.memcached.org/files/memcached-1.4.17.tar.gz
- 展開する
tar xzfv memcached-*.tar.gz
- ソースコードディレクトリへ移動する
cd memcached-*
- コンパイル最適化設定を行う
export CFLAGS="-O3 -m64"
- インストール設定を行う
インストールディレクトリ関連の設定しかないので、基本的に以下でよい。
./configure --prefix=/usr/local/memcached-1.4.17
その他のオプションは以下
[root@memcached1 memcached-1.4.17]# ./configure --help `configure' configures memcached 1.4.17 to adapt to many kinds of systems. Usage: ./configure [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print `checking...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for `--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or `..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [/usr/local] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, `make install' will install all the files in `/usr/local/bin', `/usr/local/lib' etc. You can specify an installation prefix other than `/usr/local' using `--prefix', for instance `--prefix=$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/memcached] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] --target=TARGET configure for building compilers for TARGET [HOST] Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors --enable-sasl Enable SASL authentication --enable-sasl-pwdb Enable plaintext password db --enable-dtrace Enable dtrace probes --disable-coverage Disable code coverage --enable-64bit build 64bit version --disable-docs Disable documentation generation Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-libevent=PATH Specify path to libevent installation Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a nonstandard directory <lib dir> LIBS libraries to pass to the linker, e.g. -l<library> CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if you have headers in a nonstandard directory <include dir> CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to <memcached@googlegroups.com>.
- インストールする
make 2>&1 | tee make.log make install 2>&1 | tee make_install.log
- 起動スクリプトを設定
- スクリプトを修正する
sed -e "s/\/var\/run\/memcached\/memcached.pid/\/var\/run\/memcached.pid/g" -e "s/chkconfig: - 55 45/chkconfig: 3 55 45/g" -e "s/daemon memcached/daemon \/usr\/local\/memcached\/bin\/memcached/g" scripts/memcached.sysv | egrep -v "# insure that|chown" > /etc/init.d/memcached
- パーミッションを変更する
chmod 554 /etc/init.d/memcached
- サービスに登録する
chkconfig --add memcached
- 登録を確認する
chkconfig --list memcached
- スクリプトで使用する設定ファイルを作成する
touch /usr/local/memcached-1.4.17/memcached.conf ln -s /usr/local/memcached-1.4.17/memcached.conf /etc/sysconfig/memcached echo "PORT=11211" > /etc/sysconfig/memcached echo "USER=memcached" >> /etc/sysconfig/memcached echo "MAXCONN=1024" >> /etc/sysconfig/memcached echo "CACHESIZE=64" >> /etc/sysconfig/memcached echo "OPTIONS=\"\"" >> /etc/sysconfig/memcached
- スクリプトを修正する
- 他スクリプトをコピーする
cp scripts/memcached-tool /usr/local/memcached-1.4.17/bin/ cp scripts/damemtop /usr/local/memcached-1.4.17/bin/ cp scripts/damemtop.yaml /etc/damemtop.yaml cp scripts/mc_slab_mover /usr/local/memcached-1.4.17/bin/
- インストールに使用したパッケージを削除する
cd ../ rm -rf memcached-*
- Mmemcachedのシンボリックリンクを作成する
ln -s /usr/local/memcached-1.4.17 /usr/local/memcached
これによって、複数のバージョンを同居させ、リンクを切り替えることで、バージョン変更が可能 - 共通した環境とするために環境変数を設定する
export MEMCAHCED_HOME=/usr/local/memcached
- ツール類にパスを通す
export PATH=$MEMCAHCED_HOME/bin:$PATH
- 環境変数を再起動後も有効にする
vi /etc/bashrc # 以下を追記する export MEMCAHCED_HOME=/usr/local/memcached export PATH=$MEMCAHCED_HOME/bin:$PATH
- memcachedを起動する
service memcached start
Memcachedのチューニング
起動オプション
起動オプション系は次の設定ファイルを編集することで、調整できる
vi /etc/sysconfig/memcached
現在動作している設定は次のコマンドで確認できる。
echo "stats settings" | nc 127.0.0.1 11211
基本設定
- -d
サーバモードで起動する - -s <file>
UNIXソケットを使用する場合、ソケットファイルのパスを指定する - -a <perms>
UNIXソケットファイルのパーミッションを指定する。
デフォルトは0700 - -l <ip_addr>
IP接続を使用する場合、接続を受け付けるIPアドレスを限定する - -u <username>
起動させるユーザ名を指定する。
設定ファイルではUSER項目で変更できる。 - -p <num>
TCPポート番号を指定する。
デフォルトは11211。
設定ファイルではPORT項目で変更できる。 - -U <num>
UDPポート番号を指定する。
デフォルトはTCPと同じポート番号。
0を指定することで無効に出来る。 - -P <filename>
PIDファイルのパスを指定する
並行処理
- -c <num>
同時接続可能な接続数を指定する
設定ファイルではMAXCONN項目で変更できる。 - -R <num>
1コネクションで一度に処理できる最大リクエスト数を指定する。
この数を超えると、別のコネクションの処理後に再度処理が再開される。 - -t <threads>
稼動するスレッド数を指定する。
CPUコア数以下が良いとされる。
デフォルトは4。 - -b <num>
TCPコネクション接続後にmemcachedの処理待ちとなるキュー(バックログ)のサイズ。
デフォルトは1024。
カーネルパラメータのnet.core.somaxconn値以上には設定できないので、この値を設定する場合は確認が必要。
確認する場合は次のコマンドを使用する。
sysctl net.core.somaxconn
変更する場合は次のコマンドを使用する。
sysctl -w net.core.somaxconn=<バックログ数>
変更した場合、OS起動時に初期化されるので、永続化する。
vi /etc/sysctl.conf # 以下を追記 net.core.somaxconn = <バックログ数>
オブジェクト
- -M
メモリ不足時にオブジェクトの自動削除を禁止する - -C
CASの使用を禁止する。
結果として、各オブジェクトサイズが8byteずつ減る。
メモリ
- -m <num>
使用するメモリサイズをMB単位で指定する。
デフォルトは64MB。
設定ファイルではCACHESIZE項目で変更できる。 - -k
スワップの使用を禁止する。
他のアプリケーションも含めてスワップが発生し得るほど、大きなサイズのメモリを使用する場合は注意。 - -L
ラージページを使用する。
ただし、OSがラージページをサポートしている必要がある。
大量のメモリを使用する場合、パフォーマンスが向上する。
slab設定
- -f <factor>
作成するslabは 最小のslabサイズ、最小のslabサイズ×factor値、最小のslabサイズ×factor値^2、、、となる。
ただし、slabは必ず8の倍数となるよう引き上げられる。
値を小さくすると無駄な余剰領域が小さくなる。
デフォルトは1.25 - -n <size>
chunkの最小サイズ(byte)を指定する。
デフォルトは48。 - -I <size>
slabの最大サイズを指定する。すなわち保存できるオブジェクトはこのサイズ以下となる。
デフォルトは 1mで、指定可能な範囲は 1k から 128m である。
その他
- -r
コアファイル(ダンプファイル)のサイズを上限まで引き上げる - -v
エラーや警告などを表示する。
標準出力に出力されるので、ファイルに保存する場合は次にようにする。
これは設定ファイルに記述する場合でも同様である。
-v >> /var/log/memcached.log 2>&1
- -vv
エラーや警告などを表示する。
更に実行されたコマンドとその結果も表示する - -vvv
エラーや警告などを表示する。
更に実行されたコマンドとその結果も表示する。
内部状態も表示される。 - -D <char>
prefixとID間の区切り文字を指定し、prefix毎の統計を計測する。
デフォルトの区切り文字は : であるが、統計の計測はデフォルトでは無効となっているので、
有効にする場合は stats detail on コマンドを実行する。 - -B <proto>
使用できるプロトコルを指定する。
指定できる値は以下である。
- auto
クライアントとネゴシエーションして決定する。
デフォルト - ascii
文字列を使用したリクエスト・レスポンスを行う - binary
バイナリを使用したリクエスト・レスポンスを行う。
こちらの方が高速である。
- auto
- -o <options>
試験版オプションを使用する。
,で区切って複数指定することが出来る。
使用できる機能は以下である。
- maxconns_fast
- hashpower_init
- slab_reassign
- slab_automove
オプションによるチューニング
メモリの上限設定
メモリが不足している場合、キャッシュの自動破棄が発生する。
次のコマンドでevict値が増えているかを確認
memcached-tool localhost
使用可能なメモリがある場合、使用メモリ量を増やす。
コネクション数の上限設定
UNIX SOCKETの使用
ただし、同時接続するが多くなると、エラーが発生する可能性がある。
UDPの使用
巨大なキャッシュを扱うのでなければ、TCP接続に比べ5~20倍程度高速になる。
UDPチェックサムが異なっていた場合ははきはされるが再送されないので、注意。
slabのfactor値の調整
実際にキャッシュされるオブジェクトのサイズが一様に分布している場合、
slabのfactor値が小さい方がオブジェクトとチャンクのサイズ差が小さくなり、無駄がなくなる。
ただし、そういったことは稀で、特定サイズのオブジェクトが多くキャッシュされることが多い。
その場合、殆ど使用しないサイズのslabにページを費やさないよう、factor値を調整すると良い。
例えば、100byte未満のオブジェクトを多数、100~200byteのオブジェクトを若干数、
200byte~3000byteのオブジェクトを少数保存することが想定される場合、
最小chunkサイズ(-nオプション)を100byteにした上、factorを2とすれば、100~200byteを保存するslabは
1種類にまとめることができる。
ただ、できれば1つのmemcachedに保存するオブジェクトサイズは近いものに限定した方がより調整しやすい。
例えば、キャッシュするオブジェクトが何種類もある場合(セッションデータ、データベースデータなど)、
同じ種類のデータはサイズが似通ってくるので、memcachedサーバを分割した方が良い。
コマンド
コマンドはtelnetで接続して実行するほか、ncコマンドで1つのコマンドのみ実行することもできる。
- TCP接続
echo "<コマンド>" | nc 127.0.0.1 11211
- UNIX SOCKET接続
echo "<コマンド>" | nc -U /var/run/memcached/memcached.sock
なお、ソースコードディレクトリ中に各コマンドを解説したテキストファイルがある。
cat doc/protocol.txt
内容は以下
Protocol -------- Clients of memcached communicate with server through TCP connections. (A UDP interface is also available; details are below under "UDP protocol.") A given running memcached server listens on some (configurable) port; clients connect to that port, send commands to the server, read responses, and eventually close the connection. There is no need to send any command to end the session. A client may just close the connection at any moment it no longer needs it. Note, however, that clients are encouraged to cache their connections rather than reopen them every time they need to store or retrieve data. This is because memcached is especially designed to work very efficiently with a very large number (many hundreds, more than a thousand if necessary) of open connections. Caching connections will eliminate the overhead associated with establishing a TCP connection (the overhead of preparing for a new connection on the server side is insignificant compared to this). There are two kinds of data sent in the memcache protocol: text lines and unstructured data. Text lines are used for commands from clients and responses from servers. Unstructured data is sent when a client wants to store or retrieve data. The server will transmit back unstructured data in exactly the same way it received it, as a byte stream. The server doesn't care about byte order issues in unstructured data and isn't aware of them. There are no limitations on characters that may appear in unstructured data; however, the reader of such data (either a client or a server) will always know, from a preceding text line, the exact length of the data block being transmitted. Text lines are always terminated by \r\n. Unstructured data is _also_ terminated by \r\n, even though \r, \n or any other 8-bit characters may also appear inside the data. Therefore, when a client retrieves data from a server, it must use the length of the data block (which it will be provided with) to determine where the data block ends, and not the fact that \r\n follows the end of the data block, even though it does. Keys ---- Data stored by memcached is identified with the help of a key. A key is a text string which should uniquely identify the data for clients that are interested in storing and retrieving it. Currently the length limit of a key is set at 250 characters (of course, normally clients wouldn't need to use such long keys); the key must not include control characters or whitespace. Commands -------- There are three types of commands. Storage commands (there are six: "set", "add", "replace", "append" "prepend" and "cas") ask the server to store some data identified by a key. The client sends a command line, and then a data block; after that the client expects one line of response, which will indicate success or failure. Retrieval commands (there are two: "get" and "gets") ask the server to retrieve data corresponding to a set of keys (one or more keys in one request). The client sends a command line, which includes all the requested keys; after that for each item the server finds it sends to the client one response line with information about the item, and one data block with the item's data; this continues until the server finished with the "END" response line. All other commands don't involve unstructured data. In all of them, the client sends one command line, and expects (depending on the command) either one line of response, or several lines of response ending with "END" on the last line. A command line always starts with the name of the command, followed by parameters (if any) delimited by whitespace. Command names are lower-case and are case-sensitive. Expiration times ---------------- Some commands involve a client sending some kind of expiration time (relative to an item or to an operation requested by the client) to the server. In all such cases, the actual value sent may either be Unix time (number of seconds since January 1, 1970, as a 32-bit value), or a number of seconds starting from current time. In the latter case, this number of seconds may not exceed 60*60*24*30 (number of seconds in 30 days); if the number sent by a client is larger than that, the server will consider it to be real Unix time value rather than an offset from current time. Error strings ------------- Each command sent by a client may be answered with an error string from the server. These error strings come in three types: - "ERROR\r\n" means the client sent a nonexistent command name. - "CLIENT_ERROR <error>\r\n" means some sort of client error in the input line, i.e. the input doesn't conform to the protocol in some way. <error> is a human-readable error string. - "SERVER_ERROR <error>\r\n" means some sort of server error prevents the server from carrying out the command. <error> is a human-readable error string. In cases of severe server errors, which make it impossible to continue serving the client (this shouldn't normally happen), the server will close the connection after sending the error line. This is the only case in which the server closes a connection to a client. In the descriptions of individual commands below, these error lines are not again specifically mentioned, but clients must allow for their possibility. Storage commands ---------------- First, the client sends a command line which looks like this: <command name> <key> <flags> <exptime> <bytes> [noreply]\r\n cas <key> <flags> <exptime> <bytes> <cas unique> [noreply]\r\n - <command name> is "set", "add", "replace", "append" or "prepend" "set" means "store this data". "add" means "store this data, but only if the server *doesn't* already hold data for this key". "replace" means "store this data, but only if the server *does* already hold data for this key". "append" means "add this data to an existing key after existing data". "prepend" means "add this data to an existing key before existing data". The append and prepend commands do not accept flags or exptime. They update existing data portions, and ignore new flag and exptime settings. "cas" is a check and set operation which means "store this data but only if no one else has updated since I last fetched it." - <key> is the key under which the client asks to store the data - <flags> is an arbitrary 16-bit unsigned integer (written out in decimal) that the server stores along with the data and sends back when the item is retrieved. Clients may use this as a bit field to store data-specific information; this field is opaque to the server. Note that in memcached 1.2.1 and higher, flags may be 32-bits, instead of 16, but you might want to restrict yourself to 16 bits for compatibility with older versions. - <exptime> is expiration time. If it's 0, the item never expires (although it may be deleted from the cache to make place for other items). If it's non-zero (either Unix time or offset in seconds from current time), it is guaranteed that clients will not be able to retrieve this item after the expiration time arrives (measured by server time). - <bytes> is the number of bytes in the data block to follow, *not* including the delimiting \r\n. <bytes> may be zero (in which case it's followed by an empty data block). - <cas unique> is a unique 64-bit value of an existing entry. Clients should use the value returned from the "gets" command when issuing "cas" updates. - "noreply" optional parameter instructs the server to not send the reply. NOTE: if the request line is malformed, the server can't parse "noreply" option reliably. In this case it may send the error to the client, and not reading it on the client side will break things. Client should construct only valid requests. After this line, the client sends the data block: <data block>\r\n - <data block> is a chunk of arbitrary 8-bit data of length <bytes> from the previous line. After sending the command line and the data blockm the client awaits the reply, which may be: - "STORED\r\n", to indicate success. - "NOT_STORED\r\n" to indicate the data was not stored, but not because of an error. This normally means that the condition for an "add" or a "replace" command wasn't met. - "EXISTS\r\n" to indicate that the item you are trying to store with a "cas" command has been modified since you last fetched it. - "NOT_FOUND\r\n" to indicate that the item you are trying to store with a "cas" command did not exist. Retrieval command: ------------------ The retrieval commands "get" and "gets" operates like this: get <key>*\r\n gets <key>*\r\n - <key>* means one or more key strings separated by whitespace. After this command, the client expects zero or more items, each of which is received as a text line followed by a data block. After all the items have been transmitted, the server sends the string "END\r\n" to indicate the end of response. Each item sent by the server looks like this: VALUE <key> <flags> <bytes> [<cas unique>]\r\n <data block>\r\n - <key> is the key for the item being sent - <flags> is the flags value set by the storage command - <bytes> is the length of the data block to follow, *not* including its delimiting \r\n - <cas unique> is a unique 64-bit integer that uniquely identifies this specific item. - <data block> is the data for this item. If some of the keys appearing in a retrieval request are not sent back by the server in the item list this means that the server does not hold items with such keys (because they were never stored, or stored but deleted to make space for more items, or expired, or explicitly deleted by a client). Deletion -------- The command "delete" allows for explicit deletion of items: delete <key> [noreply]\r\n - <key> is the key of the item the client wishes the server to delete - "noreply" optional parameter instructs the server to not send the reply. See the note in Storage commands regarding malformed requests. The response line to this command can be one of: - "DELETED\r\n" to indicate success - "NOT_FOUND\r\n" to indicate that the item with this key was not found. See the "flush_all" command below for immediate invalidation of all existing items. Increment/Decrement ------------------- Commands "incr" and "decr" are used to change data for some item in-place, incrementing or decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. If the current data value does not conform to such a representation, the incr/decr commands return an error (memcached <= 1.2.6 treated the bogus value as if it were 0, leading to confusion). Also, the item must already exist for incr/decr to work; these commands won't pretend that a non-existent key exists with value 0; instead, they will fail. The client sends the command line: incr <key> <value> [noreply]\r\n or decr <key> <value> [noreply]\r\n - <key> is the key of the item the client wishes to change - <value> is the amount by which the client wants to increase/decrease the item. It is a decimal representation of a 64-bit unsigned integer. - "noreply" optional parameter instructs the server to not send the reply. See the note in Storage commands regarding malformed requests. The response will be one of: - "NOT_FOUND\r\n" to indicate the item with this value was not found - <value>\r\n , where <value> is the new value of the item's data, after the increment/decrement operation was carried out. Note that underflow in the "decr" command is caught: if a client tries to decrease the value below 0, the new value will be 0. Overflow in the "incr" command will wrap around the 64 bit mark. Note also that decrementing a number such that it loses length isn't guaranteed to decrement its returned length. The number MAY be space-padded at the end, but this is purely an implementation optimization, so you also shouldn't rely on that. Touch ----- The "touch" command is used to update the expiration time of an existing item without fetching it. touch <key> <exptime> [noreply]\r\n - <key> is the key of the item the client wishes the server to delete - <exptime> is expiration time. Works the same as with the update commands (set/add/etc). This replaces the existing expiration time. If an existing item were to expire in 10 seconds, but then was touched with an expiration time of "20", the item would then expire in 20 seconds. - "noreply" optional parameter instructs the server to not send the reply. See the note in Storage commands regarding malformed requests. The response line to this command can be one of: - "TOUCHED\r\n" to indicate success - "NOT_FOUND\r\n" to indicate that the item with this key was not found. Slabs Reassign -------------- NOTE: This command is subject to change as of this writing. The slabs reassign command is used to redistribute memory once a running instance has hit its limit. It might be desireable to have memory laid out differently than was automatically assigned after the server started. slabs reassign <source class> <dest class>\r\n - <source class> is an id number for the slab class to steal a page from A source class id of -1 means "pick from any valid class" - <dest class> is an id number for the slab class to move a page to The response line could be one of: - "OK" to indicate the page has been scheduled to move - "BUSY [message]" to indicate a page is already being processed, try again later. - "BADCLASS [message]" a bad class id was specified - "NOSPARE [message]" source class has no spare pages - "NOTFULL [message]" dest class must be full to move new pages to it - "UNSAFE [message]" source class cannot move a page right now - "SAME [message]" must specify different source/dest ids. Slabs Automove -------------- NOTE: This command is subject to change as of this writing. The slabs automove command enables a background thread which decides on its own when to move memory between slab classes. Its implementation and options will likely be in flux for several versions. See the wiki/mailing list for more details. The automover can be enabled or disabled at runtime with this command. slabs automove <0|1> - 0|1|2 is the indicator on whether to enable the slabs automover or not. The response should always be "OK\r\n" - <0> means to set the thread on standby - <1> means to run the builtin slow algorithm to choose pages to move - <2> is a highly aggressive mode which causes pages to be moved every time there is an eviction. It is not recommended to run for very long in this mode unless your access patterns are very well understood. Statistics ---------- The command "stats" is used to query the server about statistics it maintains and other internal data. It has two forms. Without arguments: stats\r\n it causes the server to output general-purpose statistics and settings, documented below. In the other form it has some arguments: stats <args>\r\n Depending on <args>, various internal data is sent by the server. The kinds of arguments and the data sent are not documented in this version of the protocol, and are subject to change for the convenience of memcache developers. General-purpose statistics -------------------------- Upon receiving the "stats" command without arguments, the server sents a number of lines which look like this: STAT <name> <value>\r\n The server terminates this list with the line END\r\n In each line of statistics, <name> is the name of this statistic, and <value> is the data. The following is the list of all names sent in response to the "stats" command, together with the type of the value sent for this name, and the meaning of the value. In the type column below, "32u" means a 32-bit unsigned integer, "64u" means a 64-bit unsigned integer. '32u.32u' means two 32-bit unsigned integers separated by a colon (treat this as a floating point number). |-----------------------+---------+-------------------------------------------| | Name | Type | Meaning | |-----------------------+---------+-------------------------------------------| | pid | 32u | Process id of this server process | | uptime | 32u | Number of secs since the server started | | time | 32u | current UNIX time according to the server | | version | string | Version string of this server | | pointer_size | 32 | Default size of pointers on the host OS | | | | (generally 32 or 64) | | rusage_user | 32u.32u | Accumulated user time for this process | | | | (seconds:microseconds) | | rusage_system | 32u.32u | Accumulated system time for this process | | | | (seconds:microseconds) | | curr_items | 32u | Current number of items stored | | total_items | 32u | Total number of items stored since | | | | the server started | | bytes | 64u | Current number of bytes used | | | | to store items | | curr_connections | 32u | Number of open connections | | total_connections | 32u | Total number of connections opened since | | | | the server started running | | connection_structures | 32u | Number of connection structures allocated | | | | by the server | | reserved_fds | 32u | Number of misc fds used internally | | cmd_get | 64u | Cumulative number of retrieval reqs | | cmd_set | 64u | Cumulative number of storage reqs | | cmd_flush | 64u | Cumulative number of flush reqs | | cmd_touch | 64u | Cumulative number of touch reqs | | get_hits | 64u | Number of keys that have been requested | | | | and found present | | get_misses | 64u | Number of items that have been requested | | | | and not found | | delete_misses | 64u | Number of deletions reqs for missing keys | | delete_hits | 64u | Number of deletion reqs resulting in | | | | an item being removed. | | incr_misses | 64u | Number of incr reqs against missing keys. | | incr_hits | 64u | Number of successful incr reqs. | | decr_misses | 64u | Number of decr reqs against missing keys. | | decr_hits | 64u | Number of successful decr reqs. | | cas_misses | 64u | Number of CAS reqs against missing keys. | | cas_hits | 64u | Number of successful CAS reqs. | | cas_badval | 64u | Number of CAS reqs for which a key was | | | | found, but the CAS value did not match. | | touch_hits | 64u | Numer of keys that have been touched with | | | | a new expiration time | | touch_misses | 64u | Numer of items that have been touched and | | | | not found | | auth_cmds | 64u | Number of authentication commands | | | | handled, success or failure. | | auth_errors | 64u | Number of failed authentications. | | evictions | 64u | Number of valid items removed from cache | | | | to free memory for new items | | reclaimed | 64u | Number of times an entry was stored using | | | | memory from an expired entry | | bytes_read | 64u | Total number of bytes read by this server | | | | from network | | bytes_written | 64u | Total number of bytes sent by this server | | | | to network | | limit_maxbytes | 32u | Number of bytes this server is allowed to | | | | use for storage. | | threads | 32u | Number of worker threads requested. | | | | (see doc/threads.txt) | | conn_yields | 64u | Number of times any connection yielded to | | | | another due to hitting the -R limit. | | hash_power_level | 32u | Current size multiplier for hash table | | hash_bytes | 64u | Bytes currently used by hash tables | | hash_is_expanding | bool | Indicates if the hash table is being | | | | grown to a new size | | expired_unfetched | 64u | Items pulled from LRU that were never | | | | touched by get/incr/append/etc before | | | | expiring | | evicted_unfetched | 64u | Items evicted from LRU that were never | | | | touched by get/incr/append/etc. | | slab_reassign_running | bool | If a slab page is being moved | | slabs_moved | 64u | Total slab pages moved | |-----------------------+---------+-------------------------------------------| Settings statistics ------------------- CAVEAT: This section describes statistics which are subject to change in the future. The "stats" command with the argument of "settings" returns details of the settings of the running memcached. This is primarily made up of the results of processing commandline options. Note that these are not guaranteed to return in any specific order and this list may not be exhaustive. Otherwise, this returns like any other stats command. |-------------------+----------+----------------------------------------------| | Name | Type | Meaning | |-------------------+----------+----------------------------------------------| | maxbytes | size_t | Maximum number of bytes allows in this cache | | maxconns | 32 | Maximum number of clients allowed. | | tcpport | 32 | TCP listen port. | | udpport | 32 | UDP listen port. | | inter | string | Listen interface. | | verbosity | 32 | 0 = none, 1 = some, 2 = lots | | oldest | 32u | Age of the oldest honored object. | | evictions | on/off | When off, LRU evictions are disabled. | | domain_socket | string | Path to the domain socket (if any). | | umask | 32 (oct) | umask for the creation of the domain socket. | | growth_factor | float | Chunk size growth factor. | | chunk_size | 32 | Minimum space allocated for key+value+flags. | | num_threads | 32 | Number of threads (including dispatch). | | stat_key_prefix | char | Stats prefix separator character. | | detail_enabled | bool | If yes, stats detail is enabled. | | reqs_per_event | 32 | Max num IO ops processed within an event. | | cas_enabled | bool | When no, CAS is not enabled for this server. | | tcp_backlog | 32 | TCP listen backlog. | | auth_enabled_sasl | yes/no | SASL auth requested and enabled. | | item_size_max | size_t | maximum item size | | maxconns_fast | bool | If fast disconnects are enabled | | hashpower_init | 32 | Starting size multiplier for hash table | | slab_reassign | bool | Whether slab page reassignment is allowed | | slab_automove | bool | Whether slab page automover is enabled | |-------------------+----------+----------------------------------------------| Item statistics --------------- CAVEAT: This section describes statistics which are subject to change in the future. The "stats" command with the argument of "items" returns information about item storage per slab class. The data is returned in the format: STAT items:<slabclass>:<stat> <value>\r\n The server terminates this list with the line END\r\n The slabclass aligns with class ids used by the "stats slabs" command. Where "stats slabs" describes size and memory usage, "stats items" shows higher level information. The following item values are defined as of writing. Name Meaning ------------------------------ number Number of items presently stored in this class. Expired items are not automatically excluded. age Age of the oldest item in the LRU. evicted Number of times an item had to be evicted from the LRU before it expired. evicted_nonzero Number of times an item which had an explicit expire time set had to be evicted from the LRU before it expired. evicted_time Seconds since the last access for the most recent item evicted from this class. Use this to judge how recently active your evicted data is. outofmemory Number of times the underlying slab class was unable to store a new item. This means you are running with -M or an eviction failed. tailrepairs Number of times we self-healed a slab with a refcount leak. If this counter is increasing a lot, please report your situation to the developers. reclaimed Number of times an entry was stored using memory from an expired entry. expired_unfetched Number of expired items reclaimed from the LRU which were never touched after being set. evicted_unfetched Number of valid items evicted from the LRU which were never touched after being set. Note this will only display information about slabs which exist, so an empty cache will return an empty set. Item size statistics -------------------- CAVEAT: This section describes statistics which are subject to change in the future. The "stats" command with the argument of "sizes" returns information about the general size and count of all items stored in the cache. WARNING: This command WILL lock up your cache! It iterates over *every item* and examines the size. While the operation is fast, if you have many items you could prevent memcached from serving requests for several seconds. The data is returned in the following format: <size> <count>\r\n The server terminates this list with the line END\r\n 'size' is an approximate size of the item, within 32 bytes. 'count' is the amount of items that exist within that 32-byte range. This is essentially a display of all of your items if there was a slab class for every 32 bytes. You can use this to determine if adjusting the slab growth factor would save memory overhead. For example: generating more classes in the lower range could allow items to fit more snugly into their slab classes, if most of your items are less than 200 bytes in size. Slab statistics --------------- CAVEAT: This section describes statistics which are subject to change in the future. The "stats" command with the argument of "slabs" returns information about each of the slabs created by memcached during runtime. This includes per-slab information along with some totals. The data is returned in the format: STAT <slabclass>:<stat> <value>\r\n STAT <stat> <value>\r\n The server terminates this list with the line END\r\n |-----------------+----------------------------------------------------------| | Name | Meaning | |-----------------+----------------------------------------------------------| | chunk_size | The amount of space each chunk uses. One item will use | | | one chunk of the appropriate size. | | chunks_per_page | How many chunks exist within one page. A page by | | | default is less than or equal to one megabyte in size. | | | Slabs are allocated by page, then broken into chunks. | | total_pages | Total number of pages allocated to the slab class. | | total_chunks | Total number of chunks allocated to the slab class. | | get_hits | Total number of get requests serviced by this class. | | cmd_set | Total number of set requests storing data in this class. | | delete_hits | Total number of successful deletes from this class. | | incr_hits | Total number of incrs modifying this class. | | decr_hits | Total number of decrs modifying this class. | | cas_hits | Total number of CAS commands modifying this class. | | cas_badval | Total number of CAS commands that failed to modify a | | | value due to a bad CAS id. | | touch_hits | Total number of touches serviced by this class. | | used_chunks | How many chunks have been allocated to items. | | free_chunks | Chunks not yet allocated to items, or freed via delete. | | free_chunks_end | Number of free chunks at the end of the last allocated | | | page. | | mem_requested | Number of bytes requested to be stored in this slab[*]. | | active_slabs | Total number of slab classes allocated. | | total_malloced | Total amount of memory allocated to slab pages. | |-----------------+----------------------------------------------------------| * Items are stored in a slab that is the same size or larger than the item. mem_requested shows the size of all items within a slab. (total_chunks * chunk_size) - mem_requested shows memory wasted in a slab class. If you see a lot of waste, consider tuning the slab factor. Other commands -------------- "flush_all" is a command with an optional numeric argument. It always succeeds, and the server sends "OK\r\n" in response (unless "noreply" is given as the last parameter). Its effect is to invalidate all existing items immediately (by default) or after the expiration specified. After invalidation none of the items will be returned in response to a retrieval command (unless it's stored again under the same key *after* flush_all has invalidated the items). flush_all doesn't actually free all the memory taken up by existing items; that will happen gradually as new items are stored. The most precise definition of what flush_all does is the following: it causes all items whose update time is earlier than the time at which flush_all was set to be executed to be ignored for retrieval purposes. The intent of flush_all with a delay, was that in a setting where you have a pool of memcached servers, and you need to flush all content, you have the option of not resetting all memcached servers at the same time (which could e.g. cause a spike in database load with all clients suddenly needing to recreate content that would otherwise have been found in the memcached daemon). The delay option allows you to have them reset in e.g. 10 second intervals (by passing 0 to the first, 10 to the second, 20 to the third, etc. etc.). "version" is a command with no arguments: version\r\n In response, the server sends "VERSION <version>\r\n", where <version> is the version string for the server. "verbosity" is a command with a numeric argument. It always succeeds, and the server sends "OK\r\n" in response (unless "noreply" is given as the last parameter). Its effect is to set the verbosity level of the logging output. "quit" is a command with no arguments: quit\r\n Upon receiving this command, the server closes the connection. However, the client may also simply close the connection when it no longer needs it, without issuing this command. UDP protocol ------------ For very large installations where the number of clients is high enough that the number of TCP connections causes scaling difficulties, there is also a UDP-based interface. The UDP interface does not provide guaranteed delivery, so should only be used for operations that aren't required to succeed; typically it is used for "get" requests where a missing or incomplete response can simply be treated as a cache miss. Each UDP datagram contains a simple frame header, followed by data in the same format as the TCP protocol described above. In the current implementation, requests must be contained in a single UDP datagram, but responses may span several datagrams. (The only common requests that would span multiple datagrams are huge multi-key "get" requests and "set" requests, both of which are more suitable to TCP transport for reliability reasons anyway.) The frame header is 8 bytes long, as follows (all values are 16-bit integers in network byte order, high byte first): 0-1 Request ID 2-3 Sequence number 4-5 Total number of datagrams in this message 6-7 Reserved for future use; must be 0 The request ID is supplied by the client. Typically it will be a monotonically increasing value starting from a random seed, but the client is free to use whatever request IDs it likes. The server's response will contain the same ID as the incoming request. The client uses the request ID to differentiate between responses to outstanding requests if there are several pending from the same server; any datagrams with an unknown request ID are probably delayed responses to an earlier request and should be discarded. The sequence number ranges from 0 to n-1, where n is the total number of datagrams in the message. The client should concatenate the payloads of the datagrams for a given response in sequence number order; the resulting byte stream will contain a complete response in the same format as the TCP protocol (including terminating \r\n sequences).
データ操作
各種パラメータ
- 有効期限
正の整数で与え、Unix Timeか現在からの経過秒数を指定する。
後者の場合、最大で30日(2592000)まで指定可能で、それ以上の値はUnix Timeと認識される。
0の場合は無期限となる。
- フラグ
32bitの符号なし整数の形式で指定する。
フラグ内容は任意の内容で使用してよい。
set
- 書式
set <キー> <フラグ> <有効期限> <データサイズ> <データ内容>
get
- 書式
get <キー>
replace
setと違い、既にキーが存在する場合のみデータ格納を行う
- 書式
replace <キー> <フラグ> <有効期限> <データサイズ> <データ内容>
add
setと違い、既にキーが存在する場合はデータ格納は行わない
- 書式
add <キー> <フラグ> <有効期限> <データサイズ> <データ内容>
append
既存のデータの後に指定したデータを連結する。
フラグ、有効期限を指定する必要があるが、効果は無い。
- 書式
append <キー> <フラグ> <有効期限> <データサイズ> <データ内容>
prepend
既存のデータの前に指定したデータを連結する。
フラグ、有効期限を指定する必要があるが、効果は無い。
- 書式
prepend <キー> <フラグ> <有効期限> <データサイズ> <データ内容>
flush_all
全てのキャッシュを有効期限とする。
つまり実際にキャッシュは消えないが、次回アクセス時に無効となり、その時点で消去される。
- 書式
flush_all
ステータス確認
stats settings
起動時に指定されたオプションにより設定された内容を表示する
stats slabs
slab毎の統計値を出力する
- 実行例
STAT 1:chunk_size 248 STAT 1:chunks_per_page 2114 STAT 1:total_pages 173 STAT 1:total_chunks 365722 STAT 1:used_chunks 363997 STAT 1:free_chunks 1725 STAT 1:free_chunks_end 0 STAT 1:mem_requested 28528218 STAT 1:get_hits 0 STAT 1:cmd_set 363997 STAT 1:delete_hits 0 STAT 1:incr_hits 0 STAT 1:decr_hits 0 STAT 1:cas_hits 0 STAT 1:cas_badval 0 STAT 1:touch_hits 0 STAT 2:chunk_size 496 STAT 2:chunks_per_page 1057 STAT 2:total_pages 2 STAT 2:total_chunks 2114 STAT 2:used_chunks 2114 STAT 2:free_chunks 0 STAT 2:free_chunks_end 0 STAT 2:mem_requested 688057 STAT 2:get_hits 0 STAT 2:cmd_set 2114 STAT 2:delete_hits 0 STAT 2:incr_hits 0 STAT 2:decr_hits 0 STAT 2:cas_hits 0 STAT 2:cas_badval 0 STAT 2:touch_hits 0 STAT active_slabs 2 STAT total_malloced 91747600 END
- 出力内容
- chunk_size
chunkのサイズ - chunks_per_page
1ページあたりのchunk数 - total_pages
このslabのページ数 - total_chunks
割り当てられたページ合計で保存できるchunk数 - used_chunks
保存しているchunk数 - free_chunks
オブジェクトが割り当てられていないchunk数 - free_chunks_end
最後に割り当てられたページのオブジェクトが割り当てられていないchunk数 - mem_requested
このslabの保存データ量 - get_hits
- chunk_size
- cmd_set
- delete_hits
- incr_hits
- decr_hits
- cas_hits
- cas_badval
- touch_hits
- 全slab統計
- active_slabs
使用されているslabの種類数 - total_malloced
各ページの合計サイズ
- active_slabs
stats items
- 実行例
STAT items:1:number 363173 STAT items:1:age 7691 STAT items:1:evicted 0 STAT items:1:evicted_nonzero 0 STAT items:1:evicted_time 0 STAT items:1:outofmemory 0 STAT items:1:tailrepairs 0 STAT items:1:reclaimed 0 STAT items:1:expired_unfetched 0 STAT items:1:evicted_unfetched 0 STAT items:2:number 2114 STAT items:2:age 7749 STAT items:2:evicted 0 STAT items:2:evicted_nonzero 0 STAT items:2:evicted_time 0 STAT items:2:outofmemory 0 STAT items:2:tailrepairs 0 STAT items:2:reclaimed 0 STAT items:2:expired_unfetched 0 STAT items:2:evicted_unfetched 0 END
- 出力内容
- number
キャッシュされているオブジェクト数 - age
最も古いキャッシュの保存期間 - evicted
memcachedにより削除されたオブジェクト数 - evicted_nonzero
memcachedにより削除された有効期限が設定されていたオブジェクト数 - evicted_time
memcachedにより削除されたオブジェクトを取得しようとしてからの経過時間 - outofmemory
メモリ不足となり保存できなかったオブジェクト数(-Mオプションを使用したときのみ) - tailrepairs
- reclaimed
- expired_unfetched
- evicted_unfetched
- number
stats sizes
- 実行例
STAT 96 373482 STAT 352 2114 END
設定
stats detail on
ツール
標準ツール
memcached-tool
- 書式
- TCPを使用して接続
memcached-tool <対象ホスト>[:<ポート番号>] [コマンド]
ポート番号のデフォルトは11211である。 - UNIXソケットを使用して接続
memcached-tool <ソケットファイルパス> [コマンド]
実行するユーザはソケットファイルに対するアクセス権限が必要。
- TCPを使用して接続
- コマンドの種類
- display(デフォルト:省略可能)
SLABの使用状況を表示する - stats
ステータスを表示する - dump
キーと値のダンプを表示する
- display(デフォルト:省略可能)
damemtop
top風にmemcachedのステータスを表示するツール
mc_slab_mover
libmemcached
libmemcachedに付属するツール類
libmemcachedは以下コマンドでインストールする
yum install libmemcached
memflush
memslap
ベンチマーク測定を行うことができるツール
- 書式
- TCP/IP接続
memslap --servers <ホスト名> [オプション]
- UNIX SOCKET接続
memslap --servers /var/run/memcached/memcached.sock
- TCP/IP接続
- オプション
- –concurrency=<同時接続数>
同時接続数を指定する - –debug
デバッグ出力を行う - –quiet
結果の出力を行わない - –execute-number=<実行回数>
ベンチマークの実行回数を指定する
デフォルトは10000回 - –flag
Provide flag information for storage operation.
- –flush
開始前にflushを行う - –help
ヘルプを表示する - –initial-load=
開始前に指定した数のオブジェクトを生成する - –non-blocking
TCP接続でnon-blocking I/Oを使用する。 - –servers=
接続サーバを指定する - –tcp-nodelay
TCP接続でnodelayを使用する。 - –test=
ベンチマーク内容を指定する。指定できるのはgetもしくはsetである。 - –verbose
Give more details on the progression of the application. - –version
バージョン情報を表示する。 - –binary
バイナリプロトコルを使用する。 - –udp
UDP接続を行う
- –concurrency=<同時接続数>
memerror
memrm
memstat
指定したmemcachedのステータスを出力する
- 書式
- 対象が一台
memstat --servers=localhost
- 対象が複数
memstat --servers=<ホスト1>,<ホスト2>,,, --analyze
- 対象が一台
- 実行例
Server: localhost (11211) pid: 8918 uptime: 2469 time: 1394508172 version: 1.4.17 libevent: 2.0.18-stable pointer_size: 64 rusage_user: 3.040190 rusage_system: 4.828301 curr_connections: 3 total_connections: 4223 connection_structures: 5 reserved_fds: 20 cmd_get: 0 cmd_set: 119022 cmd_flush: 0 cmd_touch: 0 get_hits: 0 get_misses: 0 delete_misses: 0 delete_hits: 0 incr_misses: 0 incr_hits: 0 decr_misses: 0 decr_hits: 0 cas_misses: 0 cas_hits: 0 cas_badval: 0 touch_hits: 0 touch_misses: 0 auth_cmds: 0 auth_errors: 0 bytes_read: 5474489 bytes_written: 6112243 limit_maxbytes: 5368709120 accepting_conns: 1 listen_disabled_num: 0 threads: 4 conn_yields: 0 hash_power_level: 17 hash_bytes: 1048576 hash_is_expanding: 0 malloc_fails: 0 bytes: 9807349 curr_items: 119022 total_items: 119022 expired_unfetched: 0 evicted_unfetched: 0 evictions: 0 reclaimed: 0