LoginSignup
14
15

More than 5 years have passed since last update.

ElastiCacheでRedisをサポートしたのでCakePHPから使ってみた

Posted at

AWSのElastiCacheでRedisがサポートされたのでCakePHPから利用した時のメモ。
ElastiCacheでRedisは今のところ2.6.3だけみたいです。

■環境
PHP5.5.1
CakrPHP2.3.8
Redis2.6.3(redis-cli用)

まずはインストールから。redis-cliという便利なものを使うためにRedisをインストール


### Redis
# cd /usr/local/src/
# wget http://redis.googlecode.com/files/redis-2.6.3.tar.gz
# tar zxf redis-2.6.3.tar.gz
# chown -R root.root redis-2.6.3
# cd redis-2.6.3
# make

次に、PHPからRedisを使うためにphpredisをインストール


### phpredis
# cd /usr/local/src/
# git clone https://github.com/nicolasff/phpredis.git
# cd nicolasff-phpredis-0f0661e
# phpize
# ./configure
# make && make install

最後に、redisを使うためにphp.iniに追記します。


# vi /path/php.ini
extension=redis.so
# php -m | grep redis
redis
# /etc/init.d/httpd restart

ここからが本題。

CakePHPのキャッシュの設定は下記ファイルで行います。
/cakephp_path/app/Config/core.php
ただ、ファイルの内容を見てもRedisについての記載がありません。
「自前で組むしかないかー」なんて思っていたけど、探してみたら用意してありました。
CakePHPさん素敵すぎます。
/cakephp_path/lib/Cake/Cache/Engine/RedisEngine.php

用意してあるならそれを使うだけ。
core.phpに下記の内容を書き足します。


Cache::config('default', array(
    'engine'      => 'Redis',
    'prefix'      => null,
    'duration'    => 3600,
    'probability' => 100,
    'server'      => 'xxx.xxx.xxx.cache.amazonaws.com',
    'persistent'  => true,
    'compress'    => false,
));

あとは必要な箇所で呼び出すだけ。
テスト用アクションを用意してアクセスしてみます。


    public function test() {
        $key = 'test_key';
        if (!$data = Cache::read($key)) {
            Cache::set('duration', '600'); // キャッシュの時間調整
            Cache::write($key, array('test' => 'hoge'));
        }
    }

無事にセットできたか確認するためにredis-cliを使います。


# /usr/local/lib/redis/src/redis-cli -h xxx.xxx.apne1.cache.amazonaws.com
redis > keys *
1) "test_key"
2) "ElastiCacheMasterReplicationTimestamp"
redis > get test_key
"a:1:{s:4:\"test\";s:4:\"hoge\";}"
redis > ttl test_key
(integer) 582

こんな感じで値もセットできてるし、有効期間も効いています。

ただ、Redisは多機能なのに全てをサポートできてはいなさそうなので、そこはカスタマイズしていくしかなさそうです。

14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15