简介
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客户端
1
2
3
4
5
6
7
8
9
10
11 |
[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压缩包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
#解压并安装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 |
测试验证
1
2
3
4 |
|
访问http://ip/test.php
注:bak机器进行相同操作
配置缓存
配置Nginx配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 |
[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缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 |
#创建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 ). " " );
header( 'Content-Type:file' . " " );
header( 'X-cache:MISS:' . " " );
echo $data ;
}
#不存在demo文件夹则返回首页
else {
header( 'Location:../index.html' . " " );
}
?> |
注:bak机器进行相同的设置
测试验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 |
#可看出第一次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
- /*
- +———————————————————————-+
- |PHPVersion5|
- +———————————————————————-+
- |Copyright(c)1997-2004ThePHPGroup|
- +———————————————————————-+
- |Thissourcefileissubjecttoversion3.0ofthePHPlicense,|
- |thatisbundledwiththispackageinthefileLICENSE,andis|
- |availablethroughtheworld-wide-webatthefollowingurl:|
- |http://www.php.net/license/3_0.txt.|
- |IfyoudidnotreceiveacopyofthePHPlicenseandareunableto|
- |obtainitthroughtheworld-wide-web,pleasesendanoteto|
- |license@php.netsowecanmailyouacopyimmediately.|
- +———————————————————————-+
- |Author:HarunYayli<harunyayliatgmail.com>|
- +———————————————————————-+
- */
- //memcached图形化小工具
- $VERSION='$Id:memcache.php,v1.1.2.32008/08/2818:07:54miklExp$';
- #设置用户名
- define('ADMIN_USERNAME','admin');
- #设置密码
- define('ADMIN_PASSWORD','123456');
- define('DATE_FORMAT','Y/m/dH:i:s');
- define('GRAPH_SIZE',200);
- define('MAX_ITEM_DUMP',50);
- #设置memcached主机信息
- $MEMCACHE_SERVERS[]='192.168.29.133:11211';
- //////////ENDOFDEFAULTCONFIGAREA/////////////////////////////////////////////////////////////
- /////////////////Passwordprotect////////////////////////////////////////////////////////////////
- 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:Basicrealm="MemcacheLogin"");
- Header("HTTP/1.0401Unauthorized");
- echo<<<EOB
- <html><body>
- <h1>Rejected!</h1>
- <big>WrongUsernameorPassword!</big>
- </body></html>
- EOB;
- exit;
- }
- ///////////MEMCACHEFUNCTIONS/////////////////////////////////////////////////////////////////////
- functionsendMemcacheCommands($command){
- global$MEMCACHE_SERVERS;
- $result=array();
- foreach($MEMCACHE_SERVERSas$server){
- $strs=explode(':',$server);
- $host=$strs[0];
- $port=$strs[1];
- $result[$server]=sendMemcacheCommand($host,$port,$command);
- }
- return$result;
- }
- functionsendMemcacheCommand($server,$port,$command){
- $s=@fsockopen($server,$port);
- if(!$s){
- die("Cantconnectto:".$server.':'.$port);
- }
- fwrite($s,$command."");
- $buf='';
- while((!feof($s))){
- $buf.=fgets($s,256);
- if(strpos($buf,"END")!==false){//statsaysend
- break;
- }
- if(strpos($buf,"DELETED")!==false||strpos($buf,"NOT_FOUND")!==false){//deletesaysthese
- break;
- }
- if(strpos($buf,"OK")!==false){//flush_allsaysok
- break;
- }
- }
- fclose($s);
- returnparseMemcacheResults($buf);
- }
- functionparseMemcacheResults($str){
- $res=array();
- $lines=explode("",$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'){//nextlineisthevalue
- $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;
- }
- functiondumpCacheSlab($server,$slabId,$limit){
- list($host,$port)=explode(':',$server);
- $resp=sendMemcacheCommand($host,$port,'statscachedump'.$slabId.''.$limit);
- return$resp;
- }
- functionflushServer($server){
- list($host,$port)=explode(':',$server);
- $resp=sendMemcacheCommand($host,$port,'flush_all');
- return$resp;
- }
- functiongetCacheItems(){
- $items=sendMemcacheCommands('statsitems');
- $serverItems=array();
- $totalItems=array();
- foreach($itemsas$server=>$itemlist){
- $serverItems[$server]=array();
- $totalItems[$server]=0;
- if(!isset($itemlist['STAT'])){
- continue;
- }
- $iteminfo=$itemlist['STAT'];
- foreach($iteminfoas$keyinfo=>$value){
- if(preg_match('/items:(d+?):(.+?)$/',$keyinfo,$matches)){
- $serverItems[$server][$matches[1]][$matches[2]]=$value;
- if($matches[2]=='number'){
- $totalItems[$server]+=$value;
- }
- }
- }
- }
- returnarray('items'=>$serverItems,'counts'=>$totalItems);
- }
- functiongetMemcacheStats($total=true){
- $resp=sendMemcacheCommands('stats');
- if($total){
- $res=array();
- foreach($respas$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'tcachethispage
- //
- 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
- functionduration($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.="$yearsyear,";
- if($years>1)$str.="$yearsyears,";
- if($weeks==1)$str.="$weeksweek,";
- if($weeks>1)$str.="$weeksweeks,";
- if($days==1)$str.="$daysday,";
- if($days>1)$str.="$daysdays,";
- if($hours==1)$str.="$hourshourand";
- if($hours>1)$str.="$hourshoursand";
- if($mins==1)$str.="1minute";
- else$str.="$minsminutes";
- return$str;
- }
- //creategraphics
- //
- functiongraphics_avail(){
- returnextension_loaded('gd');
- }
- functionbsize($s){
- foreach(array('','K','M','G')as$i=>$k){
- if($s<1024)break;
- $s/=1024;
- }
- returnsprintf("%5.1f%sBytes",$s,$k);
- }
- //createmenuentry
- functionmenu_entry($ob,$title){
- global$PHP_SELF;
- if($ob==$_GET['op']){
- return"<li><aclass="child_active"href="$PHP_SELF&op=$ob">$title</a></li>";
- }
- return"<li><aclass="active"href="$PHP_SELF&op=$ob">$title</a></li>";
- }
- functiongetHeader(){
- $header=<<<EOB
- <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
- <html>
- <head><title>MEMCACHEINFO</title>
- <styletype="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;}
- *htmlbody{font-size:0.8em}
- *htmlp{font-size:0.8em}
- *htmltd{font-size:0.8em}
- *htmlth{font-size:0.8em}
- *htmlinput{font-size:0.8em}
- *htmlsubmit{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:1em1em1em1em;position:absolute;width:97%;z-index:100;}
- h1.memcache{background:rgb(153,153,204);margin:0;padding:0.5em1em0.5em1em;}
- *htmlh1.memcache{margin-bottom:-7px;}
- h1.memcachea:hover{text-decoration:none;color:rgb(90,90,90);}
- h1.memcachespan.logo{
- background:rgb(119,123,180);
- color:black;
- border-right:solidblack1px;
- border-bottom:solidblack1px;
- font-style:italic;
- font-size:1em;
- padding-left:1.2em;
- padding-right:1.2em;
- text-align:right;
- display:block;
- width:130px;
- }
- h1.memcachespan.logospan.name{color:white;font-size:0.7em;padding:00.8em02em;}
- h1.memcachespan.nameinfo{color:white;display:inline;font-size:0.4em;margin-left:3em;}
- h1.memcachediv.copy{color:black;font-size:0.4em;position:absolute;right:1em;}
- hr.memcache{
- background:white;
- border-bottom:solidrgb(102,102,153)1px;
- border-style:none;
- border-top:solidrgb(102,102,153)10px;
- height:12px;
- margin:0;
- margin-top:1px;
- padding:0;
- }
- ol,menu{margin:1em000;padding:0.2em;margin-left:1em;}
- ol.menuli{display:inline;margin-right:0.7em;list-style:none;font-size:85%}
- ol.menua{
- background:rgb(153,153,204);
- border:solidrgb(102,102,153)2px;
- color:white;
- font-weight:bold;
- margin-right:0em;
- padding:0.1em0.5em0.1em0.5em;
- text-decoration:none;
- margin-left:5px;
- }
- ol.menua.child_active{
- background:rgb(153,153,204);
- border:solidrgb(102,102,153)2px;
- color:white;
- font-weight:bold;
- margin-right:0em;
- padding:0.1em0.5em0.1em0.5em;
- text-decoration:none;
- border-left:solidblack5px;
- margin-left:0px;
- }
- ol.menuspan.active{
- background:rgb(153,153,204);
- border:solidrgb(102,102,153)2px;
- color:black;
- font-weight:bold;
- margin-right:0em;
- padding:0.1em0.5em0.1em0.5em;
- text-decoration:none;
- border-left:solidblack5px;
- }
- ol.menuspan.inactive{
- background:rgb(193,193,244);
- border:solidrgb(182,182,233)2px;
- color:white;
- font-weight:bold;
- margin-right:0em;
- padding:0.1em0.5em0.1em0.5em;
- text-decoration:none;
- margin-left:5px;
- }
- ol.menua:hover{
- background:rgb(193,193,244);
- text-decoration:none;
- }
- div.info{
- background:rgb(204,204,204);
- border:solidrgb(204,204,204)1px;
- margin-bottom:1em;
- }
- div.infoh2{
- background:rgb(204,204,204);
- color:black;
- font-size:1em;
- margin:0;
- padding:0.1em1em0.1em1em;
- }
- div.infotable{
- border:solidrgb(204,204,204)1px;
- border-spacing:0;
- width:100%;
- }
- div.infotableth{
- background:rgb(204,204,204);
- color:white;
- margin:0;
- padding:0.1em1em0.1em1em;
- }
- div.infotabletha.sortable{color:black;}
- div.infotabletr.tr-0{background:rgb(238,238,238);}
- div.infotabletr.tr-1{background:rgb(221,221,221);}
- div.infotabletd{padding:0.3em1em0.3em1em;}
- div.infotabletd.td-0{border-right:solidrgb(102,102,153)1px;white-space:nowrap;}
- div.infotabletd.td-n{border-right:solidrgb(102,102,153)1px;}
- div.infotabletdh3{
- color:black;
- font-size:1.1em;
- margin-left:-0.3em;
- }
- .td-0a,.td-na,.tr-0a,tr-1a{
- text-decoration:underline;
- }
- div.graph{margin-bottom:1em}
- div.graphh2{background:rgb(204,204,204);;color:black;font-size:1em;margin:0;padding:0.1em1em0.1em1em;}
- div.graphtable{border:solidrgb(204,204,204)1px;color:black;font-weight:normal;width:100%;}
- div.graphtabletd.td-0{background:rgb(238,238,238);}
- div.graphtabletd.td-1{background:rgb(221,221,221);}
- div.graphtabletd{padding:0.2em1em0.4em1em;}
- 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.5em0em1.5em2em}
- .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:blacksolid1px;
- border-right:solidblack2px;
- border-bottom:solidblack2px;
- padding:00.5em00.5em;
- margin-right:1em;
- }
- span.green{background:#60F060;padding:00.5em00.5em}
- span.red{background:#D06030;padding:00.5em00.5em}
- div.authneeded{
- background:rgb(238,238,238);
- border:solidrgb(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:solidrgb(102,102,153)2px;
- color:white;
- font-weight:bold;
- margin-right:1em;
- padding:0.1em0.5em0.1em0.5em;
- }
- //–>
- </style>
- </head>
- <body>
- <divclass="head">
- <h1class="memcache">
- <spanclass="logo"><ahref="http://pecl.php.net/package/memcache"rel="externalnofollow">memcache</a></span>
- <spanclass="nameinfo">memcache.phpby<ahref="http://livebookmark.net"rel="externalnofollow">HarunYayli</a></span>
- </h1>
- <hrclass="memcache">
- </div>
- <divclass=content>
- EOB;
- return$header;
- }
- functiongetFooter(){
- global$VERSION;
- $footer='</div><!–Basedonapc.php'.$VERSION.'–></body>
- </html>
- ';
- return$footer;
- }
- functiongetMenu(){
- global$PHP_SELF;
- echo"<olclass=menu>";
- if($_GET['op']!=4){
- echo<<<EOB
- <li><ahref="$PHP_SELF&op={$_GET['op']}"rel="externalnofollow">RefreshData</a></li>
- EOB;
- }
- else{
- echo<<<EOB
- <li><ahref="$PHP_SELF&op=2}"rel="externalnofollow">Back</a></li>
- EOB;
- }
- echo
- menu_entry(1,'ViewHostStats'),
- 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($_GETas$key=>$g){
- $_GET[$key]=htmlentities($g);
- }
- //singleout
- //whensingleoutisset,itonlygivesdetailsforthatserver.
- if(isset($_GET['singleout'])&&$_GET['singleout']>=0&&$_GET['singleout']<count($MEMCACHE_SERVERS)){
- $MEMCACHE_SERVERS=array($MEMCACHE_SERVERS[$_GET['singleout']]);
- }
- //displayimages
- if(isset($_GET['IMG'])){
- $memcacheStats=getMemcacheStats();
- $memcacheStatsSingle=getMemcacheStats(false);
- if(!graphics_avail()){
- exit(0);
- }
- functionfill_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);
- elseimagefilledrectangle($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);
- }
- }
- }
- functionfill_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")){
- //existsonlyifGD2.0.1isavaliable
- 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;//imagesize
- $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']){
- case1://piechart
- $tsize=$memcacheStats['limit_maxbytes'];
- $avail=$tsize-$memcacheStats['bytes'];
- $x=$y=$size/2;
- $angle_from=0;
- $fuzz=0.000001;
- foreach($memcacheStatsSingleas$serv=>$mcs){
- $free=$mcs['STAT']['limit_maxbytes']-$mcs['STAT']['bytes'];
- $used=$mcs['STAT']['bytes'];
- if($free>0){
- //drawfree
- $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){
- //drawused
- $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;
- case2://hitmiss
- $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;
- }
- echogetHeader();
- echogetMenu();
- switch($_GET['op']){
- case1://hoststats
- $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
- <divclass="infodiv1"><h2>GeneralCacheInformation</h2>
- <tablecellspacing=0><tbody>
- <trclass=tr-1><tdclass=td-0>PHPVersion</td><td>$phpversion</td></tr>
- EOB;
- echo"<trclass=tr-0><tdclass=td-0>MemcachedHost".((count($MEMCACHE_SERVERS)>1)?'s':'')."</td><td>";
- $i=0;
- if(!isset($_GET['singleout'])&&count($MEMCACHE_SERVERS)>1){
- foreach($MEMCACHE_SERVERSas$server){
- echo($i+1).'.<ahref="'.$PHP_SELF.'&singleout='.$i++.'"rel="externalnofollow">'.$server.'</a><br/>';
- }
- }
- else{
- echo'1.'.$MEMCACHE_SERVERS[0];
- }
- if(isset($_GET['singleout'])){
- echo'<ahref="'.$PHP_SELF.'"rel="externalnofollow">(allservers)</a><br/>';
- }
- echo"</td></tr>";
- echo"<trclass=tr-1><tdclass=td-0>TotalMemcacheCache</td><td>".bsize($memcacheStats['limit_maxbytes'])."</td></tr>";
- echo<<<EOB
- </tbody></table>
- </div>
- <divclass="infodiv1"><h2>MemcacheServerInformation</h2>
- EOB;
- foreach($MEMCACHE_SERVERSas$server){
- echo'<tablecellspacing=0><tbody>';
- echo'<trclass=tr-1><tdclass=td-1>'.$server.'</td><td><ahref="'.$PHP_SELF.'&server='.array_search($server,$MEMCACHE_SERVERS).'&op=6"rel="externalnofollow">[<b>Flushthisserver</b>]</a></td></tr>';
- echo'<trclass=tr-0><tdclass=td-0>StartTime</td><td>',date(DATE_FORMAT,$memcacheStatsSingle[$server]['STAT']['time']-$memcacheStatsSingle[$server]['STAT']['uptime']),'</td></tr>';
- echo'<trclass=tr-1><tdclass=td-0>Uptime</td><td>',duration($memcacheStatsSingle[$server]['STAT']['time']-$memcacheStatsSingle[$server]['STAT']['uptime']),'</td></tr>';
- echo'<trclass=tr-0><tdclass=td-0>MemcachedServerVersion</td><td>'.$memcacheStatsSingle[$server]['STAT']['version'].'</td></tr>';
- echo'<trclass=tr-1><tdclass=td-0>UsedCacheSize</td><td>',bsize($memcacheStatsSingle[$server]['STAT']['bytes']),'</td></tr>';
- echo'<trclass=tr-0><tdclass=td-0>TotalCacheSize</td><td>',bsize($memcacheStatsSingle[$server]['STAT']['limit_maxbytes']),'</td></tr>';
- echo'</tbody></table>';
- }
- echo<<<EOB
- </div>
- <divclass="graphdiv3"><h2>HostStatusDiagrams</h2>
- <tablecellspacing=0><tbody>
- EOB;
- $size='width='.(GRAPH_SIZE+50).'height='.(GRAPH_SIZE+10);
- echo<<<EOB
- <tr>
- <tdclass=td-0>CacheUsage</td>
- <tdclass=td-1>Hits&Misses</td>
- </tr>
- EOB;
- echo
- graphics_avail()?
- '<tr>'.
- "<tdclass=td-0><imgalt=""$sizesrc="$PHP_SELF&IMG=1&".(isset($_GET['singleout'])?'singleout='.$_GET['singleout'].'&':'')."$time"></td>".
- "<tdclass=td-1><imgalt=""$sizesrc="$PHP_SELF&IMG=2&".(isset($_GET['singleout'])?'singleout='.$_GET['singleout'].'&':'')."$time"></td></tr>"
- :"",
- '<tr>',
- '<tdclass=td-0><spanclass="greenbox"> </span>Free:',bsize($mem_avail).sprintf("(%.1f%%)",$mem_avail*100/$mem_size),"</td>",
- '<tdclass=td-1><spanclass="greenbox"> </span>Hits:',$hits.sprintf("(%.1f%%)",$hits*100/($hits+$misses)),"</td>",
- '</tr>',
- '<tr>',
- '<tdclass=td-0><spanclass="redbox"> </span>Used:',bsize($mem_used).sprintf("(%.1f%%)",$mem_used*100/$mem_size),"</td>",
- '<tdclass=td-1><spanclass="redbox"> </span>Misses:',$misses.sprintf("(%.1f%%)",$misses*100/($hits+$misses)),"</td>";
- echo<<<EOB
- </tr>
- </tbody></table>
- <br/>
- <divclass="info"><h2>CacheInformation</h2>
- <tablecellspacing=0><tbody>
- <trclass=tr-0><tdclass=td-0>CurrentItems(total)</td><td>$curr_items($total_items)</td></tr>
- <trclass=tr-1><tdclass=td-0>Hits</td><td>{$hits}</td></tr>
- <trclass=tr-0><tdclass=td-0>Misses</td><td>{$misses}</td></tr>
- <trclass=tr-1><tdclass=td-0>RequestRate(hits,misses)</td><td>$req_ratecacherequests/second</td></tr>
- <trclass=tr-0><tdclass=td-0>HitRate</td><td>$hit_ratecacherequests/second</td></tr>
- <trclass=tr-1><tdclass=td-0>MissRate</td><td>$miss_ratecacherequests/second</td></tr>
- <trclass=tr-0><tdclass=td-0>SetRate</td><td>$set_ratecacherequests/second</td></tr>
- </tbody></table>
- </div>
- EOB;
- break;
- case2://variables
- $m=0;
- $cacheItems=getCacheItems();
- $items=$cacheItems['items'];
- $totals=$cacheItems['counts'];
- $maxDump=MAX_ITEM_DUMP;
- foreach($itemsas$server=>$entries){
- echo<<<EOB
- <divclass="info"><tablecellspacing=0><tbody>
- <tr><thcolspan="2">$server</th></tr>
- <tr><th>SlabId</th><th>Info</th></tr>
- EOB;
- foreach($entriesas$slabId=>$slab){
- $dumpUrl=$PHP_SELF.'&op=2&server='.(array_search($server,$MEMCACHE_SERVERS)).'&dumpslab='.$slabId;
- echo
- "<trclass=tr-$m>",
- "<tdclass=td-0><center>",'<ahref="',$dumpUrl,'"rel="externalnofollow">',$slabId,'</a>',"</center></td>",
- "<tdclass=td-last><b>Itemcount:</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']);
- //maybesomeonelikestodoapaginationhere:)
- $i=1;
- foreach($items['ITEM']as$itemKey=>$itemInfo){
- $itemInfo=trim($itemInfo,'[]');
- echo'<ahref="',$PHP_SELF,'&op=4&server=',(array_search($server,$MEMCACHE_SERVERS)),'&key=',base64_encode($itemKey).'"rel="externalnofollow">',$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;
- case4://itemdump
- if(!isset($_GET['key'])||!isset($_GET['server'])){
- echo"Nokeyset!";
- break;
- }
- //I'mnotdoinganythingtocheckthevalidityofthekeystring.
- //probablyanexploitcanbewrittentodeleteallthefilesinkey=base64_encode("deleteall").
- //somebodyhastodoafixtothis.
- $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
- <divclass="info"><tablecellspacing=0><tbody>
- <tr><th>Server<th>Key</th><th>Value</th><th>Delete</th></tr>
- EOB;
- echo"<tr><tdclass=td-0>",$theserver,"</td><tdclass=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><ahref="',$PHP_SELF,'&op=5&server=',(int)$_GET['server'],'&key=',base64_encode($theKey),"rel="externalnofollow"">Delete</a></td>","</tr>";
- echo<<<EOB
- </tbody></table>
- </div><hr/>
- EOB;
- break;
- case5://itemdelete
- if(!isset($_GET['key'])||!isset($_GET['server'])){
- echo"Nokeyset!";
- 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;
- case6://flushserver
- $theserver=$MEMCACHE_SERVERS[(int)$_GET['server']];
- $r=flushServer($theserver);
- echo'Flush'.$theserver.":".$r;
- break;
- }
- echogetFooter();
- ?>
到此这篇关于基于Nginx的Mencached缓存配置详解的文章就介绍到这了,更多相关Nginx Mencached缓存配置内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!
原文链接:https://blog.51cto.com/14832653/2506978
相关文章
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
Java8 使用流抽取List<T> 集合中T的某个属性操作
2025-05-29 51 -
2025-05-25 19
-
2025-05-25 81
-
2025-05-27 12
-
2025-05-25 45