Memcache php提高mysql負載有效方法

來源:互聯網
上載者:User

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 '<font color="red">Cache SQL</font>:<font color="green">'.$sql.'</font><br /><br />';
} else {
echo '<font color="red">Flash SQL</font>:<font color="green">'.$sql.'</font><br /><br />';
}

$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 $)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.