Home > php教程 > php手册 > Memcache php提高mysql负载有效方法

Memcache php提高mysql负载有效方法

WBOY
Release: 2016-05-25 16:42:18
Original
1278 people have browsed it

在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方法,代码如下:

<?php
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 = &#39;&#39;) {
    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 = &#39;&#39;) {
    global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;
    $func = $type == &#39;UNBUFFERED&#39; && @function_exists(&#39;mysql_unbuffered_query&#39;) ? &#39;mysql_unbuffered_query&#39; : &#39;mysql_query&#39;;
    if (!($query = $func($sql, $this->link)) && $type != &#39;SILENT&#39;) {
        $this->halt(&#39;MySQL Query Error&#39;, $sql);
    }
    if (substr($sql, 0, 6) == &#39;SELECT&#39;) {
        echo &#39;<font color="red">Cache SQL</font>:<font color="green">&#39; . $sql . &#39;</font><br /><br />&#39;;
    } else {
        echo &#39;<font color="red">Flash SQL</font>:<font color="green">&#39; . $sql . &#39;</font><br /><br />&#39;;
    }
    $this->querynum++;
    return $query;
}
?>
Copy after login

4.将需要使用Memcache缓存的SQL查询的代码由 $db->query( 修改为 $db->query_memcache( 注意并将 while($post = $db->fetch_array($query)) { 修改为 foreach($query as $post) { 

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template