memcache mysql php_Memcache php提高mysql负载有效方法

在php mysql的web应用中我们经常会碰到上千万级的数据量,为了减轻服务器的负载我们经常会使用第三个工具来减压,下我们为你提供一款Memcache php提高mysql负载有效方法哦。

Memcache的理由:

1.Web Server(Lighttpd、Nginx据说都比Apache效率高好多,大家可以试用下)对CPU要求高,对内存要求低;而Memcached Server是对CPU要求低,对内存要求高,所以可以搭配使用。在对前端的Web Server上安装Memcached Server是可行的。

2.金钱金钱金钱,最少的付出,获得最大的收益。

3.简单简单简单,对于一个架构合理的系统来说,添加Memcache的支持可能只是一个批量处理文件的过程

Discuz!使用Memcache

1.在config.inc.php中增加

 代码如下复制代码

$memcachehost = '127.0.0.1';

$memcacheport = 11211;

$memcachelife = 60;

2.在include/common.inc.php中

$mem = new Memcache;

$mem->connect($memcachehost, $memcacheport);

3.修改include/db_mysql.class.php中的fetch_array、query这两个方法,并添加query_mysql方法,代码如下:

function fetch_array($query, $result_type = MYSQL_ASSOC) {

return is_resource($query) ? mysql_fetch_array($query, $result_type) : $query[0];

}

function query_memcache($sql, $type = '') {

global $mem,$memcachelife;

$key = md5($sql);

if(!($query = $mem->get($key))) {

$query = $this->query($sql, $type);

while($item = $this->fetch_array($query)) {

$res[] = $item;

}

$query = $res;

$mem->set($key, $query , 0, $memcachelife);

}

return $query;

}

function query($sql, $type = '') {

global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;

$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?

'mysql_unbuffered_query' : 'mysql_query';

if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {

$this->halt('MySQL Query Error', $sql);

}

if(substr($sql, 0, 6) == 'SELECT') {

echo 'Cache SQL:'.$sql.'
';

} else {

echo 'Flash SQL:'.$sql.'
';

}

$this->querynum ;

return $query;

}

4.将需要使用Memcache缓存的SQL查询的代码由

$db->query(

修改为

 代码如下复制代码
$db->query_memcache(

注意并将

 代码如下复制代码
while($post = $db->fetch_array($query)) {

修改为

 代码如下复制代码
foreach($query as $post) {

没有while的$db->fetch_array可以不用修改。

下面代码有用得着的就拿去:

preg_replace("/while([$](w )s*=s*[$]db->fetch_array([$]query))/is", "foreach($query as $\1)", $file);

回头放出个小工具批量替换下就可以了。

在EditPlus中可以这样替换:while([$](.*) = [$]db->fetch_array([$]query))替换为foreach($query as $)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值