由于ElastiCache支持Redis,我尝试从CakePHP中使用它

AWS的ElastiCache现在支持Redis,以下是我在CakePHP中使用时的笔记。
目前ElastiCache只支持Redis版本2.6.3。

■环境
PHP版本:5.5.1
CakrPHP版本:2.3.8
Redis版本:2.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路径/ app / Config / core.php
但是,即使查看文件的内容,也没有关于Redis的说明。
我曾经考虑自己构建它,但是在我开始寻找之前,它已经准备好了。
CakePHP太棒了。
/cakephp路径/ 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虽然功能多样但似乎无法支持所有需求,因此只能进行定制化处理。

bannerAds