在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中增加如下代碼:
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 />';
- }
- //開源代碼Vevb.com
- $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可以不用修改.
新聞熱點
疑難解答