首頁  >  文章  >  後端開發  >  PHP网站redis缓存方式分析

PHP网站redis缓存方式分析

WBOY
WBOY原創
2016-06-23 13:39:56781瀏覽

PHP网站redis缓存方式分析

作者:Wucl

时间:2014-02-05

章节内容:基础背景、分析内容、个人心得(这个人非常没品德,想到什么就写什么。)。

1. 基础背景:

为了提高页面访问速度,降低访问数据库压力。

2. Redis缓存分析:

首先提出3个问题:

1)是否缓存整个网站中间件的数据?

2)如果缓存整个中间件的数据redis是否可以承压?

3)PHP缓存redis是否会对中间件的缓存方式存在影响?

现有两种预案:

A方案:缓存时间较短,一般为120s以内,

B方案:缓存时间较长,一般为84600s。

A方案

开发角度:缓存操作比较频繁,但可以分担中间件部分的压力。

编辑角度:编辑数据后至多2-3分钟看到效果,因此可以不用通过操作清除缓存。

用户角度:假设以10分钟为一个时间段,那么在这个时间段里面页面加载表现为时快时慢。

B方案

开发角度:缓存不频繁,可以分担中间件很大部分的压力,建议用这个方式。

编辑角度:编辑后必须通过特定的操作清除以前的缓存。

用户角度:页面加载速度稳定且较快。

缓存与现有项目关联:

1) Redis建立连接(使用长连接):

pconnect: 类的静态变量

  

private static function getRedisObject($ip = '127.0.0.1', $port = '6379'){

try{

if(isset(static::$pconnect['redis'.$ip.$port])){

$redis = static::$pconnect['redis'.$ip.$port];

}else{

$redis = new Redis();

$redis->pconnect($ip,$port);

$redis->select(1);

static::$pconnect['redis'] = $redis;

}

try{

$redis->ping();

}catch(\RedisException $e){

$redis->pconnect($ip,$port);

$redis->select(1);

static::$pconnect['redis'] = $redis;

}

}catch(\RedisException $e){

echo $e->getMessage().'
';

}

return $redis;

}

2) 主要应用3个method:

$conn->delete ( $key )

$conn->get($key)

$conn->setex ( $key, $expire, $data )

3) 注意异常RedisException

4) 主从同步只要做一个操作:

从redis.conf修改slaveof类似为:

slaveof 127.0.0.1 6379

5) 可以master redis做添加、修改,slave redis做查询。链接阻塞以sleep解决,下列是实际项目的链接方式(参数不多做解释):

private function redisConn(){

     if(!empty(static::$memInstance['redis'] ) && static::$memInstance['redis'] instanceof Redis) {

     $cacheConn = static::$memInstance['redis'];

     try{

     $cacheConn->ping(); //链接未出异常,则返回链接实例

     return $cacheConn;

     }catch(\RedisException $e){}

     }

     $cacheConn = null;

     $tryI = 0;

     while ( $cacheConn == null && $tryI 

     try {

     $cacheConn = new Redis ();

     $serverSetting = Config::$redis;

     if (! $cacheConn->pconnect ( $serverSetting[$this->_serverType]['ip'],  $serverSetting[$this->_serverType]['port'])) {

     $this->_serverType = "default";

     $cacheConn->pconnect (  $serverSetting[$this->_serverType]['ip'],  $serverSetting[$this->_serverType]['port']);

     }

     $cacheConn->setOption ( Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE );

     // 选择DB

     $redisDB = $serverSetting[$this->_serverType]['redisDb'];

     if ($redisDB > 0 && $redisDB 

     $cacheConn->select ( $redisDB );

     } else {

     $cacheConn->select ( 0 );

     }

     } catch ( \Exception $e ) {

     sleep ( $tryI * 0.3 );

     $tryI ++;

     $cacheConn = null;

     }

     }

     static::$memInstance['redis'] = $cacheConn;

     return $cacheConn;

    }

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn