`
xitongyunwei
  • 浏览: 924108 次
文章分类
社区版块
存档分类
最新评论

PHP框架Yii系列教程(三):集成Redis

 
阅读更多

1安装Redis

切换至/usr/local/src下,下载并安装redis:

$ wgethttp://redis.googlecode.com/files/redis-2.6.12.tar.gz

$ tar xzf redis-2.6.12.tar.gz

$ cd redis-2.6.12

$ make

进入redis-2.6.12目录,修改redis.conf:

daemonize yes

启动服务端:

$src/redis-server redis.conf

进入命令行验证服务是否启动:

$src/redis-cli

redis> set foo bar

OK

redis> get foo

"bar"

2安装Yii的Redis插件

目前主要有两种Yii插件:

Ø Rediscache:基于predis(Redis的纯PHP实现客户端),无需安装Redis for PHP扩展。

Ø YiiRedis:基于phpredis客户端,需要安装Redis for PHP扩展。

这里采用Rediscache插件,避免线上安装Redis for PHP扩展。

2.1下载安装

从以下地址下载Rediscache插件:

http://www.yiiframework.com/extension/rediscache/files/redis.zip

将插件解压到helloyii/app/protected/extensions中:

插件文件部署后的位置应为:helloyii/app/protected/extensions/redis/CredisCache.php

2.2配置Rediscache

1.helloyii/app/protected/config/main.php

===============================================================================

return array(

'components' => array(

'cache'=>array(

'class'=>'ext.redis.CRedisCache', //对应protected/extensions/redis/CredisCache.php

'servers'=>array(

array(

'host'=>'127.0.0.1',

'port'=>6379,

),

),

),

),

);

3安装Yii的会话Redis插件

3.1下载安装

从GitHub上下载插件https://github.com/lincsanders/PRedisCacheHttpSession

解压到helloyii/app/protected/extensions下:

插件文件部署后的位置应为:

helloyii/app/protected/extensions/PredisCacheHttpSession/PRedisCacheHttpSession.php

3.2配置PRedisCacheHttpSession

'session'=>array(

'class' =>'ext.PRedisCacheHttpSession.PRedisCacheHttpSession',

'database' => 9,

),

注意:缓存和会话的database属性一定要区分开,用不同的Redis数据库来保存。

4编写控制器

编写一个读写缓存的控制器进行测试。

2.helloyii/app/protected/controllers/CacheController.php

===============================================================================

class CacheController extends CController

{

public function actionFetch($key, $value)

{

Yii::app()->cache->set($key, $value);

$data = Yii::app()->cache->get($key);

Yii::app()->getController()->render('result',array('data'=>$data));

}

}

3.helloyii/app/protected/views/cache/result.php

===============================================================================

<?php

echo$data;

?>

现在访问:http://helloyii.com/app/index.php?r=cache/fetch&key=a&value=b

然后通过redis-cli命令行客户端查看下缓存的变化:

可以通过redis-cli客户端查看缓存:

$ src/redis-cli

redis> keys ‘*’

参考资料

1官方安装手册

http://redis.io/download

2 Yii的Redis插件1:rediscache

http://www.yiiframework.com/extension/rediscache/

3 Yii的Redis插件2:yiiredis

https://github.com/phpnode/YiiRedis

4 Yii CCache接口的API

http://www.yiichina.com/api/CCache#get-detail

5 Redis在YiiFramework中的使用

http://denghai260.blog.163.com/blog/static/726864092012323101628773/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics