基于Nginx的Mencached缓存配置详解
程序员文章站
2022-03-19 09:20:09
简介memcached是一套分布式的高速缓存系统,memcached缺乏认证以及安全管制,这代表应该将memcached服务器放置在防火墙后。memcached的api使用三十二比特的循环冗余校验(c...
简介
memcached是一套分布式的高速缓存系统,memcached缺乏认证以及安全管制,这代表应该将memcached服务器放置在防火墙后。memcached的api使用三十二比特的循环冗余校验(crc-32)计算键值后,将数据分散在不同的机器上。当表格满了以后,接下来新增的数据会以lru机制替换掉。由于memcached通常只是当作缓存系统使用,所以使用memcached的应用程序在写回较慢的系统时(像是后端的数据库)需要额外的代码更新memcached内的数据
特征
memcached作为高速运行的分布式缓存服务器,具有以下的特点:
- 协议简单
- 基于libevent的事件处理
- 内置内存存储方式
- memcached不互相通信的分布式
前期准备
准备三台centos7虚拟机,配置ip地址和hostname,关闭防火墙和selinux,同步系统时间,修改ip地址和hostname映射
ip | hostname |
---|---|
192.168.29.132 | master |
192.168.29.138 | bak |
192.168.29.133 | mid |
master和bak机器部署nginx和php
部署memcache
mid机器部署memcached客户端
[root@mid ~]# yum install memcached -y #启动服务 [root@mid ~]# systemctl start memcached.service #查看启动情况,点击回车出现error则启动成功 [root@master ~]# telnet 192.168.29.133 11211 trying 192.168.29.133... connected to 192.168.29.133. escape character is '^]'. error
master和mid机器部署php的memcached扩展
下载libmemcached和memcached压缩包
#解压并安装libmemcached [root@master ~]#tar -xvf libmemcached-1.0.18.tar.gz [root@master ~]#cd libmemcached-1.0.18 #若编译报错,将clients/memflush.cc中报错相应位置的false改为null [root@master ~]#./configure --prefix=/usr/local/libmemcached make && make install #解压并安装memcached [root@master ~]#tar -zxvf memcached-3.1.5.tgz [root@master ~]#cd memcached-3.1.5 [root@master ~]#phpize [root@master ~]#./configure --with-libmemcached-dir=/usr/local/libmemcached --disable-memcached-sasl [root@master ~]#make && make install #完成后观察php目录下的lib/php/extensions/no-debug-zts-20170718/是否有扩展 memcached.so #添加扩展至php配置文件 [root@master ~]# vi /usr/local/php/etc/php.ini extension=memcached.so
测试验证
[root@master ~]# vi /usr/local/nginx/html/test.php <?php phpinfo(); ?>
访问http://ip/test.php
注:bak机器进行相同操作
配置缓存
配置nginx配置文件
[root@master ~]# cat /usr/local/nginx/conf/nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } #memcached缓存配置,有缓存则读取,没有缓存则报404错误 location /demo/ { set $memcached_key $request_uri; add_header x-mem-key $memcached_key; memcached_pass 192.168.29.133:11211; default_type text/html; #报错后转到特定location error_page 404 502 504 = @mymemcached; } #配置重写策略执行特定php文件 location @mymemcached { rewrite .* /demo.php?key=$request_uri; } location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param script_filename $document_root$fastcgi_script_name; include fastcgi_params; } } }
编写php文件设置memcached缓存
#创建demo文件夹 [root@master ~] mkdir /usr/local/nginx/html/demo #创建测试文件 [root@master ~] echo "123" >> /usr/local/nginx/html/demo/123.html [root@master ~]# vi /usr/local/nginx/html/demo.php <?php $fn=dirname(__file__) . $_server['request_uri']; if(file_exists($fn)){ $data=file_get_contents($fn); $m=new memcached(); $server=array( array('192.168.29.133',11211) ); $m->addservers($server); $r=$m->set($_get['key'],$data); header('content-length:'.filesize($fn)."\r\n"); header('content-type:file'."\r\n"); header('x-cache:miss:'."\r\n"); echo $data; } #不存在demo文件夹则返回首页 else{ header('location:../index.html'."\r\n"); } ?>
注:bak机器进行相同的设置
测试验证
#可看出第一次memcache中没有缓存,第二次击中缓存 [root@bak ~]# curl -i http://192.168.29.132/demo/123.html http/1.1 200 ok server: nginx/1.16.1 date: thu, 25 jun 2020 02:23:00 gmt content-type: file content-length: 4 connection: keep-alive x-powered-by: php/7.2.26 x-cache: miss: [root@bak ~]# curl -i http://192.168.29.132/demo/123.html http/1.1 200 ok server: nginx/1.16.1 date: thu, 25 jun 2020 02:23:01 gmt content-type: text/html content-length: 4 connection: keep-alive x-mem-key: /demo/123.html accept-ranges: bytes #当设置缓存后,访问相同的缓存key时,即使发起访问的机器不相同也同样能击中缓存 [root@master ~]# curl -i http://192.168.29.138/demo/123.html http/1.1 200 ok server: nginx/1.16.1 date: thu, 25 jun 2020 02:29:46 gmt content-type: text/html content-length: 4 connection: keep-alive x-mem-key: /demo/123.html accept-ranges: bytes
查看memcached缓存状态
memcached监控文件
<?php /* +----------------------------------------------------------------------+ | php version 5 | +----------------------------------------------------------------------+ | copyright (c) 1997-2004 the php group | +----------------------------------------------------------------------+ | this source file is subject to version 3.0 of the php license, | | that is bundled with this package in the file license, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_0.txt. | | if you did not receive a copy of the php license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | author: harun yayli <harunyayli at gmail.com> | +----------------------------------------------------------------------+ */ //memcached图形化小工具 $version='$id: memcache.php,v 1.1.2.3 2008/08/28 18:07:54 mikl exp $'; #设置用户名 define('admin_username','admin'); #设置密码 define('admin_password','123456'); define('date_format','y/m/d h:i:s'); define('graph_size',200); define('max_item_dump',50); #设置memcached主机信息 $memcache_servers[] = '192.168.29.133:11211'; ////////// end of default config area ///////////////////////////////////////////////////////////// ///////////////// password protect //////////////////////////////////////////////////////////////// if (!isset($_server['php_auth_user']) || !isset($_server['php_auth_pw']) || $_server['php_auth_user'] != admin_username ||$_server['php_auth_pw'] != admin_password) { header("www-authenticate: basic realm=\"memcache login\""); header("http/1.0 401 unauthorized"); echo <<<eob <html><body> <h1>rejected!</h1> <big>wrong username or password!</big> </body></html> eob; exit; } ///////////memcache functions ///////////////////////////////////////////////////////////////////// function sendmemcachecommands($command){ global $memcache_servers; $result = array(); foreach($memcache_servers as $server){ $strs = explode(':',$server); $host = $strs[0]; $port = $strs[1]; $result[$server] = sendmemcachecommand($host,$port,$command); } return $result; } function sendmemcachecommand($server,$port,$command){ $s = @fsockopen($server,$port); if (!$s){ die("cant connect to:".$server.':'.$port); } fwrite($s, $command."\r\n"); $buf=''; while ((!feof($s))) { $buf .= fgets($s, 256); if (strpos($buf,"end\r\n")!==false){ // stat says end break; } if (strpos($buf,"deleted\r\n")!==false || strpos($buf,"not_found\r\n")!==false){ // delete says these break; } if (strpos($buf,"ok\r\n")!==false){ // flush_all says ok break; } } fclose($s); return parsememcacheresults($buf); } function parsememcacheresults($str){ $res = array(); $lines = explode("\r\n",$str); $cnt = count($lines); for($i=0; $i< $cnt; $i++){ $line = $lines[$i]; $l = explode(' ',$line,3); if (count($l)==3){ $res[$l[0]][$l[1]]=$l[2]; if ($l[0]=='value'){ // next line is the value $res[$l[0]][$l[1]] = array(); list ($flag,$size)=explode(' ',$l[2]); $res[$l[0]][$l[1]]['stat']=array('flag'=>$flag,'size'=>$size); $res[$l[0]][$l[1]]['value']=$lines[++$i]; } }elseif($line=='deleted' || $line=='not_found' || $line=='ok'){ return $line; } } return $res; } function dumpcacheslab($server,$slabid,$limit){ list($host,$port) = explode(':',$server); $resp = sendmemcachecommand($host,$port,'stats cachedump '.$slabid.' '.$limit); return $resp; } function flushserver($server){ list($host,$port) = explode(':',$server); $resp = sendmemcachecommand($host,$port,'flush_all'); return $resp; } function getcacheitems(){ $items = sendmemcachecommands('stats items'); $serveritems = array(); $totalitems = array(); foreach ($items as $server=>$itemlist){ $serveritems[$server] = array(); $totalitems[$server]=0; if (!isset($itemlist['stat'])){ continue; } $iteminfo = $itemlist['stat']; foreach($iteminfo as $keyinfo=>$value){ if (preg_match('/items\:(\d+?)\:(.+?)$/',$keyinfo,$matches)){ $serveritems[$server][$matches[1]][$matches[2]] = $value; if ($matches[2]=='number'){ $totalitems[$server] +=$value; } } } } return array('items'=>$serveritems,'counts'=>$totalitems); } function getmemcachestats($total=true){ $resp = sendmemcachecommands('stats'); if ($total){ $res = array(); foreach($resp as $server=>$r){ foreach($r['stat'] as $key=>$row){ if (!isset($res[$key])){ $res[$key]=null; } switch ($key){ case 'pid': $res['pid'][$server]=$row; break; case 'uptime': $res['uptime'][$server]=$row; break; case 'time': $res['time'][$server]=$row; break; case 'version': $res['version'][$server]=$row; break; case 'pointer_size': $res['pointer_size'][$server]=$row; break; case 'rusage_user': $res['rusage_user'][$server]=$row; break; case 'rusage_system': $res['rusage_system'][$server]=$row; break; case 'curr_items': $res['curr_items']+=$row; break; case 'total_items': $res['total_items']+=$row; break; case 'bytes': $res['bytes']+=$row; break; case 'curr_connections': $res['curr_connections']+=$row; break; case 'total_connections': $res['total_connections']+=$row; break; case 'connection_structures': $res['connection_structures']+=$row; break; case 'cmd_get': $res['cmd_get']+=$row; break; case 'cmd_set': $res['cmd_set']+=$row; break; case 'get_hits': $res['get_hits']+=$row; break; case 'get_misses': $res['get_misses']+=$row; break; case 'evictions': $res['evictions']+=$row; break; case 'bytes_read': $res['bytes_read']+=$row; break; case 'bytes_written': $res['bytes_written']+=$row; break; case 'limit_maxbytes': $res['limit_maxbytes']+=$row; break; case 'threads': $res['rusage_system'][$server]=$row; break; } } } return $res; } return $resp; } ////////////////////////////////////////////////////// // // don't cache this page // header("cache-control: no-store, no-cache, must-revalidate"); // http/1.1 header("cache-control: post-check=0, pre-check=0", false); header("pragma: no-cache"); // http/1.0 function duration($ts) { global $time; $years = (int)((($time - $ts)/(7*86400))/52.177457); $rem = (int)(($time-$ts)-($years * 52.177457 * 7 * 86400)); $weeks = (int)(($rem)/(7*86400)); $days = (int)(($rem)/86400) - $weeks*7; $hours = (int)(($rem)/3600) - $days*24 - $weeks*7*24; $mins = (int)(($rem)/60) - $hours*60 - $days*24*60 - $weeks*7*24*60; $str = ''; if($years==1) $str .= "$years year, "; if($years>1) $str .= "$years years, "; if($weeks==1) $str .= "$weeks week, "; if($weeks>1) $str .= "$weeks weeks, "; if($days==1) $str .= "$days day,"; if($days>1) $str .= "$days days,"; if($hours == 1) $str .= " $hours hour and"; if($hours>1) $str .= " $hours hours and"; if($mins == 1) $str .= " 1 minute"; else $str .= " $mins minutes"; return $str; } // create graphics // function graphics_avail() { return extension_loaded('gd'); } function bsize($s) { foreach (array('','k','m','g') as $i => $k) { if ($s < 1024) break; $s/=1024; } return sprintf("%5.1f %sbytes",$s,$k); } // create menu entry function menu_entry($ob,$title) { global $php_self; if ($ob==$_get['op']){ return "<li><a class=\"child_active\" href=\"$php_self&op=$ob\">$title</a></li>"; } return "<li><a class=\"active\" href=\"$php_self&op=$ob\">$title</a></li>"; } function getheader(){ $header = <<<eob <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head><title>memcache info</title> <style type="text/css"><!-- body { background:white; font-size:100.01%; margin:0; padding:0; } body,p,td,th,input,submit { font-size:0.8em;font-family:arial,helvetica,sans-serif; } * html body {font-size:0.8em} * html p {font-size:0.8em} * html td {font-size:0.8em} * html th {font-size:0.8em} * html input {font-size:0.8em} * html submit {font-size:0.8em} td { vertical-align:top } a { color:black; font-weight:none; text-decoration:none; } a:hover { text-decoration:underline; } div.content { padding:1em 1em 1em 1em; position:absolute; width:97%; z-index:100; } h1.memcache { background:rgb(153,153,204); margin:0; padding:0.5em 1em 0.5em 1em; } * html h1.memcache { margin-bottom:-7px; } h1.memcache a:hover { text-decoration:none; color:rgb(90,90,90); } h1.memcache span.logo { background:rgb(119,123,180); color:black; border-right: solid black 1px; border-bottom: solid black 1px; font-style:italic; font-size:1em; padding-left:1.2em; padding-right:1.2em; text-align:right; display:block; width:130px; } h1.memcache span.logo span.name { color:white; font-size:0.7em; padding:0 0.8em 0 2em; } h1.memcache span.nameinfo { color:white; display:inline; font-size:0.4em; margin-left: 3em; } h1.memcache div.copy { color:black; font-size:0.4em; position:absolute; right:1em; } hr.memcache { background:white; border-bottom:solid rgb(102,102,153) 1px; border-style:none; border-top:solid rgb(102,102,153) 10px; height:12px; margin:0; margin-top:1px; padding:0; } ol,menu { margin:1em 0 0 0; padding:0.2em; margin-left:1em;} ol.menu li { display:inline; margin-right:0.7em; list-style:none; font-size:85%} ol.menu a { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:white; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; margin-left: 5px; } ol.menu a.child_active { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:white; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; border-left: solid black 5px; margin-left: 0px; } ol.menu span.active { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:black; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; border-left: solid black 5px; } ol.menu span.inactive { background:rgb(193,193,244); border:solid rgb(182,182,233) 2px; color:white; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; margin-left: 5px; } ol.menu a:hover { background:rgb(193,193,244); text-decoration:none; } div.info { background:rgb(204,204,204); border:solid rgb(204,204,204) 1px; margin-bottom:1em; } div.info h2 { background:rgb(204,204,204); color:black; font-size:1em; margin:0; padding:0.1em 1em 0.1em 1em; } div.info table { border:solid rgb(204,204,204) 1px; border-spacing:0; width:100%; } div.info table th { background:rgb(204,204,204); color:white; margin:0; padding:0.1em 1em 0.1em 1em; } div.info table th a.sortable { color:black; } div.info table tr.tr-0 { background:rgb(238,238,238); } div.info table tr.tr-1 { background:rgb(221,221,221); } div.info table td { padding:0.3em 1em 0.3em 1em; } div.info table td.td-0 { border-right:solid rgb(102,102,153) 1px; white-space:nowrap; } div.info table td.td-n { border-right:solid rgb(102,102,153) 1px; } div.info table td h3 { color:black; font-size:1.1em; margin-left:-0.3em; } .td-0 a , .td-n a, .tr-0 a , tr-1 a { text-decoration:underline; } div.graph { margin-bottom:1em } div.graph h2 { background:rgb(204,204,204);; color:black; font-size:1em; margin:0; padding:0.1em 1em 0.1em 1em; } div.graph table { border:solid rgb(204,204,204) 1px; color:black; font-weight:normal; width:100%; } div.graph table td.td-0 { background:rgb(238,238,238); } div.graph table td.td-1 { background:rgb(221,221,221); } div.graph table td { padding:0.2em 1em 0.4em 1em; } div.div1,div.div2 { margin-bottom:1em; width:35em; } div.div3 { position:absolute; left:40em; top:1em; width:580px; } //div.div3 { position:absolute; left:37em; top:1em; right:1em; } div.sorting { margin:1.5em 0em 1.5em 2em } .center { text-align:center } .aright { position:absolute;right:1em } .right { text-align:right } .ok { color:rgb(0,200,0); font-weight:bold} .failed { color:rgb(200,0,0); font-weight:bold} span.box { border: black solid 1px; border-right:solid black 2px; border-bottom:solid black 2px; padding:0 0.5em 0 0.5em; margin-right:1em; } span.green { background:#60f060; padding:0 0.5em 0 0.5em} span.red { background:#d06030; padding:0 0.5em 0 0.5em } div.authneeded { background:rgb(238,238,238); border:solid rgb(204,204,204) 1px; color:rgb(200,0,0); font-size:1.2em; font-weight:bold; padding:2em; text-align:center; } input { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:white; font-weight:bold; margin-right:1em; padding:0.1em 0.5em 0.1em 0.5em; } //--> </style> </head> <body> <div class="head"> <h1 class="memcache"> <span class="logo"><a href="http://pecl.php.net/package/memcache" rel="external nofollow" >memcache</a></span> <span class="nameinfo">memcache.php by <a href="http://livebookmark.net" rel="external nofollow" >harun yayli</a></span> </h1> <hr class="memcache"> </div> <div class=content> eob; return $header; } function getfooter(){ global $version; $footer = '</div><!-- based on apc.php '.$version.'--></body> </html> '; return $footer; } function getmenu(){ global $php_self; echo "<ol class=menu>"; if ($_get['op']!=4){ echo <<<eob <li><a href="$php_self&op={$_get['op']}" rel="external nofollow" >refresh data</a></li> eob; } else { echo <<<eob <li><a href="$php_self&op=2}" rel="external nofollow" >back</a></li> eob; } echo menu_entry(1,'view host stats'), menu_entry(2,'variables'); echo <<<eob </ol> <br/> eob; } // todo, auth $_get['op'] = !isset($_get['op'])? '1':$_get['op']; $php_self= isset($_server['php_self']) ? htmlentities(strip_tags($_server['php_self'],'')) : ''; $php_self=$php_self.'?'; $time = time(); // sanitize _get foreach($_get as $key=>$g){ $_get[$key]=htmlentities($g); } // singleout // when singleout is set, it only gives details for that server. if (isset($_get['singleout']) && $_get['singleout']>=0 && $_get['singleout'] <count($memcache_servers)){ $memcache_servers = array($memcache_servers[$_get['singleout']]); } // display images if (isset($_get['img'])){ $memcachestats = getmemcachestats(); $memcachestatssingle = getmemcachestats(false); if (!graphics_avail()) { exit(0); } function fill_box($im, $x, $y, $w, $h, $color1, $color2,$text='',$placeindex='') { global $col_black; $x1=$x+$w-1; $y1=$y+$h-1; imagerectangle($im, $x, $y1, $x1+1, $y+1, $col_black); if($y1>$y) imagefilledrectangle($im, $x, $y, $x1, $y1, $color2); else imagefilledrectangle($im, $x, $y1, $x1, $y, $color2); imagerectangle($im, $x, $y1, $x1, $y, $color1); if ($text) { if ($placeindex>0) { if ($placeindex<16) { $px=5; $py=$placeindex*12+6; imagefilledrectangle($im, $px+90, $py+3, $px+90-4, $py-3, $color2); imageline($im,$x,$y+$h/2,$px+90,$py,$color2); imagestring($im,2,$px,$py-6,$text,$color1); } else { if ($placeindex<31) { $px=$x+40*2; $py=($placeindex-15)*12+6; } else { $px=$x+40*2+100*intval(($placeindex-15)/15); $py=($placeindex%15)*12+6; } imagefilledrectangle($im, $px, $py+3, $px-4, $py-3, $color2); imageline($im,$x+$w,$y+$h/2,$px,$py,$color2); imagestring($im,2,$px+2,$py-6,$text,$color1); } } else { imagestring($im,4,$x+5,$y1-16,$text,$color1); } } } function fill_arc($im, $centerx, $centery, $diameter, $start, $end, $color1,$color2,$text='',$placeindex=0) { $r=$diameter/2; $w=deg2rad((360+$start+($end-$start)/2)%360); if (function_exists("imagefilledarc")) { // exists only if gd 2.0.1 is avaliable imagefilledarc($im, $centerx+1, $centery+1, $diameter, $diameter, $start, $end, $color1, img_arc_pie); imagefilledarc($im, $centerx, $centery, $diameter, $diameter, $start, $end, $color2, img_arc_pie); imagefilledarc($im, $centerx, $centery, $diameter, $diameter, $start, $end, $color1, img_arc_nofill|img_arc_edged); } else { imagearc($im, $centerx, $centery, $diameter, $diameter, $start, $end, $color2); imageline($im, $centerx, $centery, $centerx + cos(deg2rad($start)) * $r, $centery + sin(deg2rad($start)) * $r, $color2); imageline($im, $centerx, $centery, $centerx + cos(deg2rad($start+1)) * $r, $centery + sin(deg2rad($start)) * $r, $color2); imageline($im, $centerx, $centery, $centerx + cos(deg2rad($end-1)) * $r, $centery + sin(deg2rad($end)) * $r, $color2); imageline($im, $centerx, $centery, $centerx + cos(deg2rad($end)) * $r, $centery + sin(deg2rad($end)) * $r, $color2); imagefill($im,$centerx + $r*cos($w)/2, $centery + $r*sin($w)/2, $color2); } if ($text) { if ($placeindex>0) { imageline($im,$centerx + $r*cos($w)/2, $centery + $r*sin($w)/2,$diameter, $placeindex*12,$color1); imagestring($im,4,$diameter, $placeindex*12,$text,$color1); } else { imagestring($im,4,$centerx + $r*cos($w)/2, $centery + $r*sin($w)/2,$text,$color1); } } } $size = graph_size; // image size $image = imagecreate($size+50, $size+10); $col_white = imagecolorallocate($image, 0xff, 0xff, 0xff); $col_red = imagecolorallocate($image, 0xd0, 0x60, 0x30); $col_green = imagecolorallocate($image, 0x60, 0xf0, 0x60); $col_black = imagecolorallocate($image, 0, 0, 0); imagecolortransparent($image,$col_white); switch ($_get['img']){ case 1: // pie chart $tsize=$memcachestats['limit_maxbytes']; $avail=$tsize-$memcachestats['bytes']; $x=$y=$size/2; $angle_from = 0; $fuzz = 0.000001; foreach($memcachestatssingle as $serv=>$mcs) { $free = $mcs['stat']['limit_maxbytes']-$mcs['stat']['bytes']; $used = $mcs['stat']['bytes']; if ($free>0){ // draw free $angle_to = ($free*360)/$tsize; $perc =sprintf("%.2f%%", ($free *100) / $tsize) ; fill_arc($image,$x,$y,$size,$angle_from,$angle_from + $angle_to ,$col_black,$col_green,$perc); $angle_from = $angle_from + $angle_to ; } if ($used>0){ // draw used $angle_to = ($used*360)/$tsize; $perc =sprintf("%.2f%%", ($used *100) / $tsize) ; fill_arc($image,$x,$y,$size,$angle_from,$angle_from + $angle_to ,$col_black,$col_red, '('.$perc.')' ); $angle_from = $angle_from+ $angle_to ; } } break; case 2: // hit miss $hits = ($memcachestats['get_hits']==0) ? 1:$memcachestats['get_hits']; $misses = ($memcachestats['get_misses']==0) ? 1:$memcachestats['get_misses']; $total = $hits + $misses ; fill_box($image, 30,$size,50,-$hits*($size-21)/$total,$col_black,$col_green,sprintf("%.1f%%",$hits*100/$total)); fill_box($image,130,$size,50,-max(4,($total-$hits)*($size-21)/$total),$col_black,$col_red,sprintf("%.1f%%",$misses*100/$total)); break; } header("content-type: image/png"); imagepng($image); exit; } echo getheader(); echo getmenu(); switch ($_get['op']) { case 1: // host stats $phpversion = phpversion(); $memcachestats = getmemcachestats(); $memcachestatssingle = getmemcachestats(false); $mem_size = $memcachestats['limit_maxbytes']; $mem_used = $memcachestats['bytes']; $mem_avail= $mem_size-$mem_used; $starttime = time()-array_sum($memcachestats['uptime']); $curr_items = $memcachestats['curr_items']; $total_items = $memcachestats['total_items']; $hits = ($memcachestats['get_hits']==0) ? 1:$memcachestats['get_hits']; $misses = ($memcachestats['get_misses']==0) ? 1:$memcachestats['get_misses']; $sets = $memcachestats['cmd_set']; $req_rate = sprintf("%.2f",($hits+$misses)/($time-$starttime)); $hit_rate = sprintf("%.2f",($hits)/($time-$starttime)); $miss_rate = sprintf("%.2f",($misses)/($time-$starttime)); $set_rate = sprintf("%.2f",($sets)/($time-$starttime)); echo <<< eob <div class="info div1"><h2>general cache information</h2> <table cellspacing=0><tbody> <tr class=tr-1><td class=td-0>php version</td><td>$phpversion</td></tr> eob; echo "<tr class=tr-0><td class=td-0>memcached host". ((count($memcache_servers)>1) ? 's':'')."</td><td>"; $i=0; if (!isset($_get['singleout']) && count($memcache_servers)>1){ foreach($memcache_servers as $server){ echo ($i+1).'. <a href="'.$php_self.'&singleout='.$i++.'" rel="external nofollow" >'.$server.'</a><br/>'; } } else{ echo '1.'.$memcache_servers[0]; } if (isset($_get['singleout'])){ echo '<a href="'.$php_self.'" rel="external nofollow" >(all servers)</a><br/>'; } echo "</td></tr>\n"; echo "<tr class=tr-1><td class=td-0>total memcache cache</td><td>".bsize($memcachestats['limit_maxbytes'])."</td></tr>\n"; echo <<<eob </tbody></table> </div> <div class="info div1"><h2>memcache server information</h2> eob; foreach($memcache_servers as $server){ echo '<table cellspacing=0><tbody>'; echo '<tr class=tr-1><td class=td-1>'.$server.'</td><td><a href="'.$php_self.'&server='.array_search($server,$memcache_servers).'&op=6" rel="external nofollow" >[<b>flush this server</b>]</a></td></tr>'; echo '<tr class=tr-0><td class=td-0>start time</td><td>',date(date_format,$memcachestatssingle[$server]['stat']['time']-$memcachestatssingle[$server]['stat']['uptime']),'</td></tr>'; echo '<tr class=tr-1><td class=td-0>uptime</td><td>',duration($memcachestatssingle[$server]['stat']['time']-$memcachestatssingle[$server]['stat']['uptime']),'</td></tr>'; echo '<tr class=tr-0><td class=td-0>memcached server version</td><td>'.$memcachestatssingle[$server]['stat']['version'].'</td></tr>'; echo '<tr class=tr-1><td class=td-0>used cache size</td><td>',bsize($memcachestatssingle[$server]['stat']['bytes']),'</td></tr>'; echo '<tr class=tr-0><td class=td-0>total cache size</td><td>',bsize($memcachestatssingle[$server]['stat']['limit_maxbytes']),'</td></tr>'; echo '</tbody></table>'; } echo <<<eob </div> <div class="graph div3"><h2>host status diagrams</h2> <table cellspacing=0><tbody> eob; $size='width='.(graph_size+50).' height='.(graph_size+10); echo <<<eob <tr> <td class=td-0>cache usage</td> <td class=td-1>hits & misses</td> </tr> eob; echo graphics_avail() ? '<tr>'. "<td class=td-0><img alt=\"\" $size src=\"$php_self&img=1&".(isset($_get['singleout'])? 'singleout='.$_get['singleout'].'&':'')."$time\"></td>". "<td class=td-1><img alt=\"\" $size src=\"$php_self&img=2&".(isset($_get['singleout'])? 'singleout='.$_get['singleout'].'&':'')."$time\"></td></tr>\n" : "", '<tr>', '<td class=td-0><span class="green box"> </span>free: ',bsize($mem_avail).sprintf(" (%.1f%%)",$mem_avail*100/$mem_size),"</td>\n", '<td class=td-1><span class="green box"> </span>hits: ',$hits.sprintf(" (%.1f%%)",$hits*100/($hits+$misses)),"</td>\n", '</tr>', '<tr>', '<td class=td-0><span class="red box"> </span>used: ',bsize($mem_used ).sprintf(" (%.1f%%)",$mem_used *100/$mem_size),"</td>\n", '<td class=td-1><span class="red box"> </span>misses: ',$misses.sprintf(" (%.1f%%)",$misses*100/($hits+$misses)),"</td>\n"; echo <<< eob </tr> </tbody></table> <br/> <div class="info"><h2>cache information</h2> <table cellspacing=0><tbody> <tr class=tr-0><td class=td-0>current items(total)</td><td>$curr_items ($total_items)</td></tr> <tr class=tr-1><td class=td-0>hits</td><td>{$hits}</td></tr> <tr class=tr-0><td class=td-0>misses</td><td>{$misses}</td></tr> <tr class=tr-1><td class=td-0>request rate (hits, misses)</td><td>$req_rate cache requests/second</td></tr> <tr class=tr-0><td class=td-0>hit rate</td><td>$hit_rate cache requests/second</td></tr> <tr class=tr-1><td class=td-0>miss rate</td><td>$miss_rate cache requests/second</td></tr> <tr class=tr-0><td class=td-0>set rate</td><td>$set_rate cache requests/second</td></tr> </tbody></table> </div> eob; break; case 2: // variables $m=0; $cacheitems= getcacheitems(); $items = $cacheitems['items']; $totals = $cacheitems['counts']; $maxdump = max_item_dump; foreach($items as $server => $entries) { echo <<< eob <div class="info"><table cellspacing=0><tbody> <tr><th colspan="2">$server</th></tr> <tr><th>slab id</th><th>info</th></tr> eob; foreach($entries as $slabid => $slab) { $dumpurl = $php_self.'&op=2&server='.(array_search($server,$memcache_servers)).'&dumpslab='.$slabid; echo "<tr class=tr-$m>", "<td class=td-0><center>",'<a href="',$dumpurl,'" rel="external nofollow" >',$slabid,'</a>',"</center></td>", "<td class=td-last><b>item count:</b> ",$slab['number'],'<br/><b>age:</b>',duration($time-$slab['age']),'<br/> <b>evicted:</b>',((isset($slab['evicted']) && $slab['evicted']==1)? 'yes':'no'); if ((isset($_get['dumpslab']) && $_get['dumpslab']==$slabid) && (isset($_get['server']) && $_get['server']==array_search($server,$memcache_servers))){ echo "<br/><b>items: item</b><br/>"; $items = dumpcacheslab($server,$slabid,$slab['number']); // maybe someone likes to do a pagination here :) $i=1; foreach($items['item'] as $itemkey=>$iteminfo){ $iteminfo = trim($iteminfo,'[ ]'); echo '<a href="',$php_self,'&op=4&server=',(array_search($server,$memcache_servers)),'&key=',base64_encode($itemkey).'" rel="external nofollow" >',$itemkey,'</a>'; if ($i++ % 10 == 0) { echo '<br/>'; } elseif ($i!=$slab['number']+1){ echo ','; } } } echo "</td></tr>"; $m=1-$m; } echo <<<eob </tbody></table> </div><hr/> eob; } break; break; case 4: //item dump if (!isset($_get['key']) || !isset($_get['server'])){ echo "no key set!"; break; } // i'm not doing anything to check the validity of the key string. // probably an exploit can be written to delete all the files in key=base64_encode("\n\r delete all"). // somebody has to do a fix to this. $thekey = htmlentities(base64_decode($_get['key'])); $theserver = $memcache_servers[(int)$_get['server']]; list($h,$p) = explode(':',$theserver); $r = sendmemcachecommand($h,$p,'get '.$thekey); echo <<<eob <div class="info"><table cellspacing=0><tbody> <tr><th>server<th>key</th><th>value</th><th>delete</th></tr> eob; echo "<tr><td class=td-0>",$theserver,"</td><td class=td-0>",$thekey, " <br/>flag:",$r['value'][$thekey]['stat']['flag'], " <br/>size:",bsize($r['value'][$thekey]['stat']['size']), "</td><td>",chunk_split($r['value'][$thekey]['value'],40),"</td>", '<td><a href="',$php_self,'&op=5&server=',(int)$_get['server'],'&key=',base64_encode($thekey)," rel="external nofollow" \">delete</a></td>","</tr>"; echo <<<eob </tbody></table> </div><hr/> eob; break; case 5: // item delete if (!isset($_get['key']) || !isset($_get['server'])){ echo "no key set!"; break; } $thekey = htmlentities(base64_decode($_get['key'])); $theserver = $memcache_servers[(int)$_get['server']]; list($h,$p) = explode(':',$theserver); $r = sendmemcachecommand($h,$p,'delete '.$thekey); echo 'deleting '.$thekey.':'.$r; break; case 6: // flush server $theserver = $memcache_servers[(int)$_get['server']]; $r = flushserver($theserver); echo 'flush '.$theserver.":".$r; break; } echo getfooter(); ?>
到此这篇关于基于nginx的mencached缓存配置详解的文章就介绍到这了,更多相关nginx mencached缓存配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: Nginx Linux安装部署详细教程
推荐阅读