edo1z blog

プログラミングなどに関するブログです

EC2 cakePHPでMemcachedつかう

AmazonLinuxにMemcachedを設定します。

インストールと設定

インストールします。 参考:さくらの VPS 設定覚書(4)PHP

yum --enablerepo=remi,epel,rpmforge install libevent libevent-devel memcached php-pecl-memcache php-pecl-memcached

設定します。

vim /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="4096"
CACHESIZE="2048"
OPTIONS=""

Memcached を起動します。

service memcached start

自動起動の設定をします。

chkconfig --add memcached
chkconfig memcached on
chkconfig --list memcached

“0:off 1:off 2:on 3:on 4:on 5:on 6:off”と出れば、設定成功です。

memcache.iniを設定します。 http://php.net/manual/ja/memcache.ini.php

vim /etc/php.d/memcache.ini
memcache.chunk_size=32768
memcache.default_port=11211
session.save_path="tcp://localhost:11211"

Apacheを再起動します。 service httpd restart

php -R ' phpinfo(); exit(); ' | grep "memcache" で、反映してるか確認できます。

EC2でポートをあける

Custom TCP Rule, tcp, 11211, セキュリティグループ

cakePHPでつかえるようにする

core.phpで下記がコメントアウトされてるので、コメントを外します。

Cache::config('default', array(
    'engine' => 'Memcache', //[required]
    'duration' => 3600, //[optional]
    'probability' => 100, //[optional]
    'prefix' => Inflector::slug(APP_DIR) . '_', //[optional]  prefix every cache file with this string
    'servers' => array(
        '127.0.0.1:11211' // localhost, default port 11211
    ), //[optional]
    'persistent' => true, // [optional] set this to false for non-persistent connections
    'compress' => false, // [optional] compress data in Memcache (slower, but uses less memory)
));

あとは、キャッシュを使いたいところで、App::uses('Cache', 'Cache');を書いて、Cache::read('hoge');とか、Cache::write('hoge', 123);とかやります。

memcachedは、apacheを再起動しても消えないけど、memcachedを再起動したら消えます。あとcakePHPのCacheは、モデルが追加、編集、削除されたときにモデルに関するキャッシュを消すそうです。でもroutes.phpでURL変えてると消えない場合があるようです。