php专区

 首页 > php专区 > PHP应用 > 常用功能 > Memcache php提高mysql负载有效方法 - php高级应用

Memcache php提高mysql负载有效方法 - php高级应用

分享到:
【字体:大 中 小】
导读:
          在php mysql的web应用中我们经常会碰到上千万级的数据量,为了减轻服务器的负载我们经常会使用第三个工具来减压,下我们为你提供一款Memcache php提高mysql负载有效方法.Memcache的理由:1.Web...

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

  1. function fetch_array($query, $result_type = MYSQL_ASSOC) { 
  2. return is_resource($query) ? mysql_fetch_array($query, $result_type) : $query[0]; 
  3. } 
  4.  
  5. function query_memcache($sql, $type = '') { 
  6. global $mem,$memcachelife; 
  7.  
  8. $key = md5($sql); 
  9. if(!($query = $mem->get($key))) { 
  10. $query = $this->query($sql, $type); 
  11. while($item = $this->fetch_array($query)) { 
  12. $res[] = $item; 
  13. } 
  14. $query = $res; 
  15. $mem->set($key, $query , 0, $memcachelife); 
  16. } 
  17. return $query; 
  18. } 
  19.  
  20. function query($sql, $type = '') { 
  21. global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes; 
  22.  
  23. $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 
  24. 'mysql_unbuffered_query' : 'mysql_query'; 
  25. if(!($query = $func($sql, $this->link)) && $type != 'SILENT') { 
  26. $this->halt('MySQL Query Error', $sql); 
  27. } 
  28.  
  29. if(substr($sql, 0, 6) == 'SELECT') { 
  30. echo 'Cache SQL:'.$sql.''; 
  31. } else { 
  32. echo 'Flash SQL:'.$sql.''; 
  33. } 
  34. //开源代码phpfensi.com 
  35. $this->querynum++; 
  36. return $query; 
  37. } 

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

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

分享到:
xmllint命令处理xml与html的例子 - php高...
xmllint命令处理xml与html的例子 xmllint是一个很方便的处理及验证xml、处理html的工具,linux下只要安装libxml2就可以使用这个命令,首先看下其结合--html、--xpath参数处理html时的例子. 例子:curl http://www.phpfensi.com /ip/?q=8.8.8.8 2>/dev/null | xmllint --html --xpath "//ul[@id=...
PHP调用linux命令详细说明 - php高级应用
PHP调用linux命令详细说明 在php中调用linux命令的函数是 string exec(string command,string[array],int[return_var]);  如:exec( "vpopmail ");echo exec('whoami');   再看一实例,代码如下: function exec_enabled() {    $disabled = explode(', &#...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……