基于Nginx的Mencached缓存配置详解

2025-05-26 0 19

简介

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
[root@master ~]# vi /usr/local/nginx/html/test.php

<?php

phpinfo();

?>

访问http://ip/test.php

基于Nginx的Mencached缓存配置详解

注: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缓存状态

基于Nginx的Mencached缓存配置详解

基于Nginx的Mencached缓存配置详解

memcached监控文件

  1. <?php
  2. /*
  3. +———————————————————————-+
  4. |PHPVersion5|
  5. +———————————————————————-+
  6. |Copyright(c)1997-2004ThePHPGroup|
  7. +———————————————————————-+
  8. |Thissourcefileissubjecttoversion3.0ofthePHPlicense,|
  9. |thatisbundledwiththispackageinthefileLICENSE,andis|
  10. |availablethroughtheworld-wide-webatthefollowingurl:|
  11. |http://www.php.net/license/3_0.txt.|
  12. |IfyoudidnotreceiveacopyofthePHPlicenseandareunableto|
  13. |obtainitthroughtheworld-wide-web,pleasesendanoteto|
  14. |license@php.netsowecanmailyouacopyimmediately.|
  15. +———————————————————————-+
  16. |Author:HarunYayli<harunyayliatgmail.com>|
  17. +———————————————————————-+
  18. */
  19. //memcached图形化小工具
  20. $VERSION='$Id:memcache.php,v1.1.2.32008/08/2818:07:54miklExp$';
  21. #设置用户名
  22. define('ADMIN_USERNAME','admin');
  23. #设置密码
  24. define('ADMIN_PASSWORD','123456');
  25. define('DATE_FORMAT','Y/m/dH:i:s');
  26. define('GRAPH_SIZE',200);
  27. define('MAX_ITEM_DUMP',50);
  28. #设置memcached主机信息
  29. $MEMCACHE_SERVERS[]='192.168.29.133:11211';
  30. //////////ENDOFDEFAULTCONFIGAREA/////////////////////////////////////////////////////////////
  31. /////////////////Passwordprotect////////////////////////////////////////////////////////////////
  32. if(!isset($_SERVER['PHP_AUTH_USER'])||!isset($_SERVER['PHP_AUTH_PW'])||
  33. $_SERVER['PHP_AUTH_USER']!=ADMIN_USERNAME||$_SERVER['PHP_AUTH_PW']!=ADMIN_PASSWORD){
  34. Header("WWW-Authenticate:Basicrealm="MemcacheLogin"");
  35. Header("HTTP/1.0401Unauthorized");
  36. echo<<<EOB
  37. <html><body>
  38. <h1>Rejected!</h1>
  39. <big>WrongUsernameorPassword!</big>
  40. </body></html>
  41. EOB;
  42. exit;
  43. }
  44. ///////////MEMCACHEFUNCTIONS/////////////////////////////////////////////////////////////////////
  45. functionsendMemcacheCommands($command){
  46. global$MEMCACHE_SERVERS;
  47. $result=array();
  48. foreach($MEMCACHE_SERVERSas$server){
  49. $strs=explode(':',$server);
  50. $host=$strs[0];
  51. $port=$strs[1];
  52. $result[$server]=sendMemcacheCommand($host,$port,$command);
  53. }
  54. return$result;
  55. }
  56. functionsendMemcacheCommand($server,$port,$command){
  57. $s=@fsockopen($server,$port);
  58. if(!$s){
  59. die("Cantconnectto:".$server.':'.$port);
  60. }
  61. fwrite($s,$command."");
  62. $buf='';
  63. while((!feof($s))){
  64. $buf.=fgets($s,256);
  65. if(strpos($buf,"END")!==false){//statsaysend
  66. break;
  67. }
  68. if(strpos($buf,"DELETED")!==false||strpos($buf,"NOT_FOUND")!==false){//deletesaysthese
  69. break;
  70. }
  71. if(strpos($buf,"OK")!==false){//flush_allsaysok
  72. break;
  73. }
  74. }
  75. fclose($s);
  76. returnparseMemcacheResults($buf);
  77. }
  78. functionparseMemcacheResults($str){
  79. $res=array();
  80. $lines=explode("",$str);
  81. $cnt=count($lines);
  82. for($i=0;$i<$cnt;$i++){
  83. $line=$lines[$i];
  84. $l=explode('',$line,3);
  85. if(count($l)==3){
  86. $res[$l[0]][$l[1]]=$l[2];
  87. if($l[0]=='VALUE'){//nextlineisthevalue
  88. $res[$l[0]][$l[1]]=array();
  89. list($flag,$size)=explode('',$l[2]);
  90. $res[$l[0]][$l[1]]['stat']=array('flag'=>$flag,'size'=>$size);
  91. $res[$l[0]][$l[1]]['value']=$lines[++$i];
  92. }
  93. }elseif($line=='DELETED'||$line=='NOT_FOUND'||$line=='OK'){
  94. return$line;
  95. }
  96. }
  97. return$res;
  98. }
  99. functiondumpCacheSlab($server,$slabId,$limit){
  100. list($host,$port)=explode(':',$server);
  101. $resp=sendMemcacheCommand($host,$port,'statscachedump'.$slabId.''.$limit);
  102. return$resp;
  103. }
  104. functionflushServer($server){
  105. list($host,$port)=explode(':',$server);
  106. $resp=sendMemcacheCommand($host,$port,'flush_all');
  107. return$resp;
  108. }
  109. functiongetCacheItems(){
  110. $items=sendMemcacheCommands('statsitems');
  111. $serverItems=array();
  112. $totalItems=array();
  113. foreach($itemsas$server=>$itemlist){
  114. $serverItems[$server]=array();
  115. $totalItems[$server]=0;
  116. if(!isset($itemlist['STAT'])){
  117. continue;
  118. }
  119. $iteminfo=$itemlist['STAT'];
  120. foreach($iteminfoas$keyinfo=>$value){
  121. if(preg_match('/items:(d+?):(.+?)$/',$keyinfo,$matches)){
  122. $serverItems[$server][$matches[1]][$matches[2]]=$value;
  123. if($matches[2]=='number'){
  124. $totalItems[$server]+=$value;
  125. }
  126. }
  127. }
  128. }
  129. returnarray('items'=>$serverItems,'counts'=>$totalItems);
  130. }
  131. functiongetMemcacheStats($total=true){
  132. $resp=sendMemcacheCommands('stats');
  133. if($total){
  134. $res=array();
  135. foreach($respas$server=>$r){
  136. foreach($r['STAT']as$key=>$row){
  137. if(!isset($res[$key])){
  138. $res[$key]=null;
  139. }
  140. switch($key){
  141. case'pid':
  142. $res['pid'][$server]=$row;
  143. break;
  144. case'uptime':
  145. $res['uptime'][$server]=$row;
  146. break;
  147. case'time':
  148. $res['time'][$server]=$row;
  149. break;
  150. case'version':
  151. $res['version'][$server]=$row;
  152. break;
  153. case'pointer_size':
  154. $res['pointer_size'][$server]=$row;
  155. break;
  156. case'rusage_user':
  157. $res['rusage_user'][$server]=$row;
  158. break;
  159. case'rusage_system':
  160. $res['rusage_system'][$server]=$row;
  161. break;
  162. case'curr_items':
  163. $res['curr_items']+=$row;
  164. break;
  165. case'total_items':
  166. $res['total_items']+=$row;
  167. break;
  168. case'bytes':
  169. $res['bytes']+=$row;
  170. break;
  171. case'curr_connections':
  172. $res['curr_connections']+=$row;
  173. break;
  174. case'total_connections':
  175. $res['total_connections']+=$row;
  176. break;
  177. case'connection_structures':
  178. $res['connection_structures']+=$row;
  179. break;
  180. case'cmd_get':
  181. $res['cmd_get']+=$row;
  182. break;
  183. case'cmd_set':
  184. $res['cmd_set']+=$row;
  185. break;
  186. case'get_hits':
  187. $res['get_hits']+=$row;
  188. break;
  189. case'get_misses':
  190. $res['get_misses']+=$row;
  191. break;
  192. case'evictions':
  193. $res['evictions']+=$row;
  194. break;
  195. case'bytes_read':
  196. $res['bytes_read']+=$row;
  197. break;
  198. case'bytes_written':
  199. $res['bytes_written']+=$row;
  200. break;
  201. case'limit_maxbytes':
  202. $res['limit_maxbytes']+=$row;
  203. break;
  204. case'threads':
  205. $res['rusage_system'][$server]=$row;
  206. break;
  207. }
  208. }
  209. }
  210. return$res;
  211. }
  212. return$resp;
  213. }
  214. //////////////////////////////////////////////////////
  215. //
  216. //don'tcachethispage
  217. //
  218. header("Cache-Control:no-store,no-cache,must-revalidate");//HTTP/1.1
  219. header("Cache-Control:post-check=0,pre-check=0",false);
  220. header("Pragma:no-cache");//HTTP/1.0
  221. functionduration($ts){
  222. global$time;
  223. $years=(int)((($time-$ts)/(7*86400))/52.177457);
  224. $rem=(int)(($time-$ts)-($years*52.177457*7*86400));
  225. $weeks=(int)(($rem)/(7*86400));
  226. $days=(int)(($rem)/86400)-$weeks*7;
  227. $hours=(int)(($rem)/3600)-$days*24-$weeks*7*24;
  228. $mins=(int)(($rem)/60)-$hours*60-$days*24*60-$weeks*7*24*60;
  229. $str='';
  230. if($years==1)$str.="$yearsyear,";
  231. if($years>1)$str.="$yearsyears,";
  232. if($weeks==1)$str.="$weeksweek,";
  233. if($weeks>1)$str.="$weeksweeks,";
  234. if($days==1)$str.="$daysday,";
  235. if($days>1)$str.="$daysdays,";
  236. if($hours==1)$str.="$hourshourand";
  237. if($hours>1)$str.="$hourshoursand";
  238. if($mins==1)$str.="1minute";
  239. else$str.="$minsminutes";
  240. return$str;
  241. }
  242. //creategraphics
  243. //
  244. functiongraphics_avail(){
  245. returnextension_loaded('gd');
  246. }
  247. functionbsize($s){
  248. foreach(array('','K','M','G')as$i=>$k){
  249. if($s<1024)break;
  250. $s/=1024;
  251. }
  252. returnsprintf("%5.1f%sBytes",$s,$k);
  253. }
  254. //createmenuentry
  255. functionmenu_entry($ob,$title){
  256. global$PHP_SELF;
  257. if($ob==$_GET['op']){
  258. return"<li><aclass="child_active"href="$PHP_SELF&op=$ob">$title</a></li>";
  259. }
  260. return"<li><aclass="active"href="$PHP_SELF&op=$ob">$title</a></li>";
  261. }
  262. functiongetHeader(){
  263. $header=<<<EOB
  264. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  265. <html>
  266. <head><title>MEMCACHEINFO</title>
  267. <styletype="text/css"><!–
  268. body{background:white;font-size:100.01%;margin:0;padding:0;}
  269. body,p,td,th,input,submit{font-size:0.8em;font-family:arial,helvetica,sans-serif;}
  270. *htmlbody{font-size:0.8em}
  271. *htmlp{font-size:0.8em}
  272. *htmltd{font-size:0.8em}
  273. *htmlth{font-size:0.8em}
  274. *htmlinput{font-size:0.8em}
  275. *htmlsubmit{font-size:0.8em}
  276. td{vertical-align:top}
  277. a{color:black;font-weight:none;text-decoration:none;}
  278. a:hover{text-decoration:underline;}
  279. div.content{padding:1em1em1em1em;position:absolute;width:97%;z-index:100;}
  280. h1.memcache{background:rgb(153,153,204);margin:0;padding:0.5em1em0.5em1em;}
  281. *htmlh1.memcache{margin-bottom:-7px;}
  282. h1.memcachea:hover{text-decoration:none;color:rgb(90,90,90);}
  283. h1.memcachespan.logo{
  284. background:rgb(119,123,180);
  285. color:black;
  286. border-right:solidblack1px;
  287. border-bottom:solidblack1px;
  288. font-style:italic;
  289. font-size:1em;
  290. padding-left:1.2em;
  291. padding-right:1.2em;
  292. text-align:right;
  293. display:block;
  294. width:130px;
  295. }
  296. h1.memcachespan.logospan.name{color:white;font-size:0.7em;padding:00.8em02em;}
  297. h1.memcachespan.nameinfo{color:white;display:inline;font-size:0.4em;margin-left:3em;}
  298. h1.memcachediv.copy{color:black;font-size:0.4em;position:absolute;right:1em;}
  299. hr.memcache{
  300. background:white;
  301. border-bottom:solidrgb(102,102,153)1px;
  302. border-style:none;
  303. border-top:solidrgb(102,102,153)10px;
  304. height:12px;
  305. margin:0;
  306. margin-top:1px;
  307. padding:0;
  308. }
  309. ol,menu{margin:1em000;padding:0.2em;margin-left:1em;}
  310. ol.menuli{display:inline;margin-right:0.7em;list-style:none;font-size:85%}
  311. ol.menua{
  312. background:rgb(153,153,204);
  313. border:solidrgb(102,102,153)2px;
  314. color:white;
  315. font-weight:bold;
  316. margin-right:0em;
  317. padding:0.1em0.5em0.1em0.5em;
  318. text-decoration:none;
  319. margin-left:5px;
  320. }
  321. ol.menua.child_active{
  322. background:rgb(153,153,204);
  323. border:solidrgb(102,102,153)2px;
  324. color:white;
  325. font-weight:bold;
  326. margin-right:0em;
  327. padding:0.1em0.5em0.1em0.5em;
  328. text-decoration:none;
  329. border-left:solidblack5px;
  330. margin-left:0px;
  331. }
  332. ol.menuspan.active{
  333. background:rgb(153,153,204);
  334. border:solidrgb(102,102,153)2px;
  335. color:black;
  336. font-weight:bold;
  337. margin-right:0em;
  338. padding:0.1em0.5em0.1em0.5em;
  339. text-decoration:none;
  340. border-left:solidblack5px;
  341. }
  342. ol.menuspan.inactive{
  343. background:rgb(193,193,244);
  344. border:solidrgb(182,182,233)2px;
  345. color:white;
  346. font-weight:bold;
  347. margin-right:0em;
  348. padding:0.1em0.5em0.1em0.5em;
  349. text-decoration:none;
  350. margin-left:5px;
  351. }
  352. ol.menua:hover{
  353. background:rgb(193,193,244);
  354. text-decoration:none;
  355. }
  356. div.info{
  357. background:rgb(204,204,204);
  358. border:solidrgb(204,204,204)1px;
  359. margin-bottom:1em;
  360. }
  361. div.infoh2{
  362. background:rgb(204,204,204);
  363. color:black;
  364. font-size:1em;
  365. margin:0;
  366. padding:0.1em1em0.1em1em;
  367. }
  368. div.infotable{
  369. border:solidrgb(204,204,204)1px;
  370. border-spacing:0;
  371. width:100%;
  372. }
  373. div.infotableth{
  374. background:rgb(204,204,204);
  375. color:white;
  376. margin:0;
  377. padding:0.1em1em0.1em1em;
  378. }
  379. div.infotabletha.sortable{color:black;}
  380. div.infotabletr.tr-0{background:rgb(238,238,238);}
  381. div.infotabletr.tr-1{background:rgb(221,221,221);}
  382. div.infotabletd{padding:0.3em1em0.3em1em;}
  383. div.infotabletd.td-0{border-right:solidrgb(102,102,153)1px;white-space:nowrap;}
  384. div.infotabletd.td-n{border-right:solidrgb(102,102,153)1px;}
  385. div.infotabletdh3{
  386. color:black;
  387. font-size:1.1em;
  388. margin-left:-0.3em;
  389. }
  390. .td-0a,.td-na,.tr-0a,tr-1a{
  391. text-decoration:underline;
  392. }
  393. div.graph{margin-bottom:1em}
  394. div.graphh2{background:rgb(204,204,204);;color:black;font-size:1em;margin:0;padding:0.1em1em0.1em1em;}
  395. div.graphtable{border:solidrgb(204,204,204)1px;color:black;font-weight:normal;width:100%;}
  396. div.graphtabletd.td-0{background:rgb(238,238,238);}
  397. div.graphtabletd.td-1{background:rgb(221,221,221);}
  398. div.graphtabletd{padding:0.2em1em0.4em1em;}
  399. div.div1,div.div2{margin-bottom:1em;width:35em;}
  400. div.div3{position:absolute;left:40em;top:1em;width:580px;}
  401. //div.div3{position:absolute;left:37em;top:1em;right:1em;}
  402. div.sorting{margin:1.5em0em1.5em2em}
  403. .center{text-align:center}
  404. .aright{position:absolute;right:1em}
  405. .right{text-align:right}
  406. .ok{color:rgb(0,200,0);font-weight:bold}
  407. .failed{color:rgb(200,0,0);font-weight:bold}
  408. span.box{
  409. border:blacksolid1px;
  410. border-right:solidblack2px;
  411. border-bottom:solidblack2px;
  412. padding:00.5em00.5em;
  413. margin-right:1em;
  414. }
  415. span.green{background:#60F060;padding:00.5em00.5em}
  416. span.red{background:#D06030;padding:00.5em00.5em}
  417. div.authneeded{
  418. background:rgb(238,238,238);
  419. border:solidrgb(204,204,204)1px;
  420. color:rgb(200,0,0);
  421. font-size:1.2em;
  422. font-weight:bold;
  423. padding:2em;
  424. text-align:center;
  425. }
  426. input{
  427. background:rgb(153,153,204);
  428. border:solidrgb(102,102,153)2px;
  429. color:white;
  430. font-weight:bold;
  431. margin-right:1em;
  432. padding:0.1em0.5em0.1em0.5em;
  433. }
  434. //–>
  435. </style>
  436. </head>
  437. <body>
  438. <divclass="head">
  439. <h1class="memcache">
  440. <spanclass="logo"><ahref="http://pecl.php.net/package/memcache"rel="externalnofollow">memcache</a></span>
  441. <spanclass="nameinfo">memcache.phpby<ahref="http://livebookmark.net"rel="externalnofollow">HarunYayli</a></span>
  442. </h1>
  443. <hrclass="memcache">
  444. </div>
  445. <divclass=content>
  446. EOB;
  447. return$header;
  448. }
  449. functiongetFooter(){
  450. global$VERSION;
  451. $footer='</div><!–Basedonapc.php'.$VERSION.'–></body>
  452. </html>
  453. ';
  454. return$footer;
  455. }
  456. functiongetMenu(){
  457. global$PHP_SELF;
  458. echo"<olclass=menu>";
  459. if($_GET['op']!=4){
  460. echo<<<EOB
  461. <li><ahref="$PHP_SELF&op={$_GET['op']}"rel="externalnofollow">RefreshData</a></li>
  462. EOB;
  463. }
  464. else{
  465. echo<<<EOB
  466. <li><ahref="$PHP_SELF&op=2}"rel="externalnofollow">Back</a></li>
  467. EOB;
  468. }
  469. echo
  470. menu_entry(1,'ViewHostStats'),
  471. menu_entry(2,'Variables');
  472. echo<<<EOB
  473. </ol>
  474. <br/>
  475. EOB;
  476. }
  477. //TODO,AUTH
  478. $_GET['op']=!isset($_GET['op'])?'1':$_GET['op'];
  479. $PHP_SELF=isset($_SERVER['PHP_SELF'])?htmlentities(strip_tags($_SERVER['PHP_SELF'],'')):'';
  480. $PHP_SELF=$PHP_SELF.'?';
  481. $time=time();
  482. //sanitize_GET
  483. foreach($_GETas$key=>$g){
  484. $_GET[$key]=htmlentities($g);
  485. }
  486. //singleout
  487. //whensingleoutisset,itonlygivesdetailsforthatserver.
  488. if(isset($_GET['singleout'])&&$_GET['singleout']>=0&&$_GET['singleout']<count($MEMCACHE_SERVERS)){
  489. $MEMCACHE_SERVERS=array($MEMCACHE_SERVERS[$_GET['singleout']]);
  490. }
  491. //displayimages
  492. if(isset($_GET['IMG'])){
  493. $memcacheStats=getMemcacheStats();
  494. $memcacheStatsSingle=getMemcacheStats(false);
  495. if(!graphics_avail()){
  496. exit(0);
  497. }
  498. functionfill_box($im,$x,$y,$w,$h,$color1,$color2,$text='',$placeindex=''){
  499. global$col_black;
  500. $x1=$x+$w-1;
  501. $y1=$y+$h-1;
  502. imagerectangle($im,$x,$y1,$x1+1,$y+1,$col_black);
  503. if($y1>$y)imagefilledrectangle($im,$x,$y,$x1,$y1,$color2);
  504. elseimagefilledrectangle($im,$x,$y1,$x1,$y,$color2);
  505. imagerectangle($im,$x,$y1,$x1,$y,$color1);
  506. if($text){
  507. if($placeindex>0){
  508. if($placeindex<16)
  509. {
  510. $px=5;
  511. $py=$placeindex*12+6;
  512. imagefilledrectangle($im,$px+90,$py+3,$px+90-4,$py-3,$color2);
  513. imageline($im,$x,$y+$h/2,$px+90,$py,$color2);
  514. imagestring($im,2,$px,$py-6,$text,$color1);
  515. }else{
  516. if($placeindex<31){
  517. $px=$x+40*2;
  518. $py=($placeindex-15)*12+6;
  519. }else{
  520. $px=$x+40*2+100*intval(($placeindex-15)/15);
  521. $py=($placeindex%15)*12+6;
  522. }
  523. imagefilledrectangle($im,$px,$py+3,$px-4,$py-3,$color2);
  524. imageline($im,$x+$w,$y+$h/2,$px,$py,$color2);
  525. imagestring($im,2,$px+2,$py-6,$text,$color1);
  526. }
  527. }else{
  528. imagestring($im,4,$x+5,$y1-16,$text,$color1);
  529. }
  530. }
  531. }
  532. functionfill_arc($im,$centerX,$centerY,$diameter,$start,$end,$color1,$color2,$text='',$placeindex=0){
  533. $r=$diameter/2;
  534. $w=deg2rad((360+$start+($end-$start)/2)%360);
  535. if(function_exists("imagefilledarc")){
  536. //existsonlyifGD2.0.1isavaliable
  537. imagefilledarc($im,$centerX+1,$centerY+1,$diameter,$diameter,$start,$end,$color1,IMG_ARC_PIE);
  538. imagefilledarc($im,$centerX,$centerY,$diameter,$diameter,$start,$end,$color2,IMG_ARC_PIE);
  539. imagefilledarc($im,$centerX,$centerY,$diameter,$diameter,$start,$end,$color1,IMG_ARC_NOFILL|IMG_ARC_EDGED);
  540. }else{
  541. imagearc($im,$centerX,$centerY,$diameter,$diameter,$start,$end,$color2);
  542. imageline($im,$centerX,$centerY,$centerX+cos(deg2rad($start))*$r,$centerY+sin(deg2rad($start))*$r,$color2);
  543. imageline($im,$centerX,$centerY,$centerX+cos(deg2rad($start+1))*$r,$centerY+sin(deg2rad($start))*$r,$color2);
  544. imageline($im,$centerX,$centerY,$centerX+cos(deg2rad($end-1))*$r,$centerY+sin(deg2rad($end))*$r,$color2);
  545. imageline($im,$centerX,$centerY,$centerX+cos(deg2rad($end))*$r,$centerY+sin(deg2rad($end))*$r,$color2);
  546. imagefill($im,$centerX+$r*cos($w)/2,$centerY+$r*sin($w)/2,$color2);
  547. }
  548. if($text){
  549. if($placeindex>0){
  550. imageline($im,$centerX+$r*cos($w)/2,$centerY+$r*sin($w)/2,$diameter,$placeindex*12,$color1);
  551. imagestring($im,4,$diameter,$placeindex*12,$text,$color1);
  552. }else{
  553. imagestring($im,4,$centerX+$r*cos($w)/2,$centerY+$r*sin($w)/2,$text,$color1);
  554. }
  555. }
  556. }
  557. $size=GRAPH_SIZE;//imagesize
  558. $image=imagecreate($size+50,$size+10);
  559. $col_white=imagecolorallocate($image,0xFF,0xFF,0xFF);
  560. $col_red=imagecolorallocate($image,0xD0,0x60,0x30);
  561. $col_green=imagecolorallocate($image,0x60,0xF0,0x60);
  562. $col_black=imagecolorallocate($image,0,0,0);
  563. imagecolortransparent($image,$col_white);
  564. switch($_GET['IMG']){
  565. case1://piechart
  566. $tsize=$memcacheStats['limit_maxbytes'];
  567. $avail=$tsize-$memcacheStats['bytes'];
  568. $x=$y=$size/2;
  569. $angle_from=0;
  570. $fuzz=0.000001;
  571. foreach($memcacheStatsSingleas$serv=>$mcs){
  572. $free=$mcs['STAT']['limit_maxbytes']-$mcs['STAT']['bytes'];
  573. $used=$mcs['STAT']['bytes'];
  574. if($free>0){
  575. //drawfree
  576. $angle_to=($free*360)/$tsize;
  577. $perc=sprintf("%.2f%%",($free*100)/$tsize);
  578. fill_arc($image,$x,$y,$size,$angle_from,$angle_from+$angle_to,$col_black,$col_green,$perc);
  579. $angle_from=$angle_from+$angle_to;
  580. }
  581. if($used>0){
  582. //drawused
  583. $angle_to=($used*360)/$tsize;
  584. $perc=sprintf("%.2f%%",($used*100)/$tsize);
  585. fill_arc($image,$x,$y,$size,$angle_from,$angle_from+$angle_to,$col_black,$col_red,'('.$perc.')');
  586. $angle_from=$angle_from+$angle_to;
  587. }
  588. }
  589. break;
  590. case2://hitmiss
  591. $hits=($memcacheStats['get_hits']==0)?1:$memcacheStats['get_hits'];
  592. $misses=($memcacheStats['get_misses']==0)?1:$memcacheStats['get_misses'];
  593. $total=$hits+$misses;
  594. fill_box($image,30,$size,50,-$hits*($size-21)/$total,$col_black,$col_green,sprintf("%.1f%%",$hits*100/$total));
  595. fill_box($image,130,$size,50,-max(4,($total-$hits)*($size-21)/$total),$col_black,$col_red,sprintf("%.1f%%",$misses*100/$total));
  596. break;
  597. }
  598. header("Content-type:image/png");
  599. imagepng($image);
  600. exit;
  601. }
  602. echogetHeader();
  603. echogetMenu();
  604. switch($_GET['op']){
  605. case1://hoststats
  606. $phpversion=phpversion();
  607. $memcacheStats=getMemcacheStats();
  608. $memcacheStatsSingle=getMemcacheStats(false);
  609. $mem_size=$memcacheStats['limit_maxbytes'];
  610. $mem_used=$memcacheStats['bytes'];
  611. $mem_avail=$mem_size-$mem_used;
  612. $startTime=time()-array_sum($memcacheStats['uptime']);
  613. $curr_items=$memcacheStats['curr_items'];
  614. $total_items=$memcacheStats['total_items'];
  615. $hits=($memcacheStats['get_hits']==0)?1:$memcacheStats['get_hits'];
  616. $misses=($memcacheStats['get_misses']==0)?1:$memcacheStats['get_misses'];
  617. $sets=$memcacheStats['cmd_set'];
  618. $req_rate=sprintf("%.2f",($hits+$misses)/($time-$startTime));
  619. $hit_rate=sprintf("%.2f",($hits)/($time-$startTime));
  620. $miss_rate=sprintf("%.2f",($misses)/($time-$startTime));
  621. $set_rate=sprintf("%.2f",($sets)/($time-$startTime));
  622. echo<<<EOB
  623. <divclass="infodiv1"><h2>GeneralCacheInformation</h2>
  624. <tablecellspacing=0><tbody>
  625. <trclass=tr-1><tdclass=td-0>PHPVersion</td><td>$phpversion</td></tr>
  626. EOB;
  627. echo"<trclass=tr-0><tdclass=td-0>MemcachedHost".((count($MEMCACHE_SERVERS)>1)?'s':'')."</td><td>";
  628. $i=0;
  629. if(!isset($_GET['singleout'])&&count($MEMCACHE_SERVERS)>1){
  630. foreach($MEMCACHE_SERVERSas$server){
  631. echo($i+1).'.<ahref="'.$PHP_SELF.'&singleout='.$i++.'"rel="externalnofollow">'.$server.'</a><br/>';
  632. }
  633. }
  634. else{
  635. echo'1.'.$MEMCACHE_SERVERS[0];
  636. }
  637. if(isset($_GET['singleout'])){
  638. echo'<ahref="'.$PHP_SELF.'"rel="externalnofollow">(allservers)</a><br/>';
  639. }
  640. echo"</td></tr>";
  641. echo"<trclass=tr-1><tdclass=td-0>TotalMemcacheCache</td><td>".bsize($memcacheStats['limit_maxbytes'])."</td></tr>";
  642. echo<<<EOB
  643. </tbody></table>
  644. </div>
  645. <divclass="infodiv1"><h2>MemcacheServerInformation</h2>
  646. EOB;
  647. foreach($MEMCACHE_SERVERSas$server){
  648. echo'<tablecellspacing=0><tbody>';
  649. 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>';
  650. echo'<trclass=tr-0><tdclass=td-0>StartTime</td><td>',date(DATE_FORMAT,$memcacheStatsSingle[$server]['STAT']['time']-$memcacheStatsSingle[$server]['STAT']['uptime']),'</td></tr>';
  651. echo'<trclass=tr-1><tdclass=td-0>Uptime</td><td>',duration($memcacheStatsSingle[$server]['STAT']['time']-$memcacheStatsSingle[$server]['STAT']['uptime']),'</td></tr>';
  652. echo'<trclass=tr-0><tdclass=td-0>MemcachedServerVersion</td><td>'.$memcacheStatsSingle[$server]['STAT']['version'].'</td></tr>';
  653. echo'<trclass=tr-1><tdclass=td-0>UsedCacheSize</td><td>',bsize($memcacheStatsSingle[$server]['STAT']['bytes']),'</td></tr>';
  654. echo'<trclass=tr-0><tdclass=td-0>TotalCacheSize</td><td>',bsize($memcacheStatsSingle[$server]['STAT']['limit_maxbytes']),'</td></tr>';
  655. echo'</tbody></table>';
  656. }
  657. echo<<<EOB
  658. </div>
  659. <divclass="graphdiv3"><h2>HostStatusDiagrams</h2>
  660. <tablecellspacing=0><tbody>
  661. EOB;
  662. $size='width='.(GRAPH_SIZE+50).'height='.(GRAPH_SIZE+10);
  663. echo<<<EOB
  664. <tr>
  665. <tdclass=td-0>CacheUsage</td>
  666. <tdclass=td-1>Hits&amp;Misses</td>
  667. </tr>
  668. EOB;
  669. echo
  670. graphics_avail()?
  671. '<tr>'.
  672. "<tdclass=td-0><imgalt=""$sizesrc="$PHP_SELF&IMG=1&".(isset($_GET['singleout'])?'singleout='.$_GET['singleout'].'&':'')."$time"></td>".
  673. "<tdclass=td-1><imgalt=""$sizesrc="$PHP_SELF&IMG=2&".(isset($_GET['singleout'])?'singleout='.$_GET['singleout'].'&':'')."$time"></td></tr>"
  674. :"",
  675. '<tr>',
  676. '<tdclass=td-0><spanclass="greenbox">&nbsp;</span>Free:',bsize($mem_avail).sprintf("(%.1f%%)",$mem_avail*100/$mem_size),"</td>",
  677. '<tdclass=td-1><spanclass="greenbox">&nbsp;</span>Hits:',$hits.sprintf("(%.1f%%)",$hits*100/($hits+$misses)),"</td>",
  678. '</tr>',
  679. '<tr>',
  680. '<tdclass=td-0><spanclass="redbox">&nbsp;</span>Used:',bsize($mem_used).sprintf("(%.1f%%)",$mem_used*100/$mem_size),"</td>",
  681. '<tdclass=td-1><spanclass="redbox">&nbsp;</span>Misses:',$misses.sprintf("(%.1f%%)",$misses*100/($hits+$misses)),"</td>";
  682. echo<<<EOB
  683. </tr>
  684. </tbody></table>
  685. <br/>
  686. <divclass="info"><h2>CacheInformation</h2>
  687. <tablecellspacing=0><tbody>
  688. <trclass=tr-0><tdclass=td-0>CurrentItems(total)</td><td>$curr_items($total_items)</td></tr>
  689. <trclass=tr-1><tdclass=td-0>Hits</td><td>{$hits}</td></tr>
  690. <trclass=tr-0><tdclass=td-0>Misses</td><td>{$misses}</td></tr>
  691. <trclass=tr-1><tdclass=td-0>RequestRate(hits,misses)</td><td>$req_ratecacherequests/second</td></tr>
  692. <trclass=tr-0><tdclass=td-0>HitRate</td><td>$hit_ratecacherequests/second</td></tr>
  693. <trclass=tr-1><tdclass=td-0>MissRate</td><td>$miss_ratecacherequests/second</td></tr>
  694. <trclass=tr-0><tdclass=td-0>SetRate</td><td>$set_ratecacherequests/second</td></tr>
  695. </tbody></table>
  696. </div>
  697. EOB;
  698. break;
  699. case2://variables
  700. $m=0;
  701. $cacheItems=getCacheItems();
  702. $items=$cacheItems['items'];
  703. $totals=$cacheItems['counts'];
  704. $maxDump=MAX_ITEM_DUMP;
  705. foreach($itemsas$server=>$entries){
  706. echo<<<EOB
  707. <divclass="info"><tablecellspacing=0><tbody>
  708. <tr><thcolspan="2">$server</th></tr>
  709. <tr><th>SlabId</th><th>Info</th></tr>
  710. EOB;
  711. foreach($entriesas$slabId=>$slab){
  712. $dumpUrl=$PHP_SELF.'&op=2&server='.(array_search($server,$MEMCACHE_SERVERS)).'&dumpslab='.$slabId;
  713. echo
  714. "<trclass=tr-$m>",
  715. "<tdclass=td-0><center>",'<ahref="',$dumpUrl,'"rel="externalnofollow">',$slabId,'</a>',"</center></td>",
  716. "<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');
  717. if((isset($_GET['dumpslab'])&&$_GET['dumpslab']==$slabId)&&(isset($_GET['server'])&&$_GET['server']==array_search($server,$MEMCACHE_SERVERS))){
  718. echo"<br/><b>Items:item</b><br/>";
  719. $items=dumpCacheSlab($server,$slabId,$slab['number']);
  720. //maybesomeonelikestodoapaginationhere:)
  721. $i=1;
  722. foreach($items['ITEM']as$itemKey=>$itemInfo){
  723. $itemInfo=trim($itemInfo,'[]');
  724. echo'<ahref="',$PHP_SELF,'&op=4&server=',(array_search($server,$MEMCACHE_SERVERS)),'&key=',base64_encode($itemKey).'"rel="externalnofollow">',$itemKey,'</a>';
  725. if($i++%10==0){
  726. echo'<br/>';
  727. }
  728. elseif($i!=$slab['number']+1){
  729. echo',';
  730. }
  731. }
  732. }
  733. echo"</td></tr>";
  734. $m=1-$m;
  735. }
  736. echo<<<EOB
  737. </tbody></table>
  738. </div><hr/>
  739. EOB;
  740. }
  741. break;
  742. break;
  743. case4://itemdump
  744. if(!isset($_GET['key'])||!isset($_GET['server'])){
  745. echo"Nokeyset!";
  746. break;
  747. }
  748. //I'mnotdoinganythingtocheckthevalidityofthekeystring.
  749. //probablyanexploitcanbewrittentodeleteallthefilesinkey=base64_encode("deleteall").
  750. //somebodyhastodoafixtothis.
  751. $theKey=htmlentities(base64_decode($_GET['key']));
  752. $theserver=$MEMCACHE_SERVERS[(int)$_GET['server']];
  753. list($h,$p)=explode(':',$theserver);
  754. $r=sendMemcacheCommand($h,$p,'get'.$theKey);
  755. echo<<<EOB
  756. <divclass="info"><tablecellspacing=0><tbody>
  757. <tr><th>Server<th>Key</th><th>Value</th><th>Delete</th></tr>
  758. EOB;
  759. echo"<tr><tdclass=td-0>",$theserver,"</td><tdclass=td-0>",$theKey,
  760. "<br/>flag:",$r['VALUE'][$theKey]['stat']['flag'],
  761. "<br/>Size:",bsize($r['VALUE'][$theKey]['stat']['size']),
  762. "</td><td>",chunk_split($r['VALUE'][$theKey]['value'],40),"</td>",
  763. '<td><ahref="',$PHP_SELF,'&op=5&server=',(int)$_GET['server'],'&key=',base64_encode($theKey),"rel="externalnofollow"">Delete</a></td>","</tr>";
  764. echo<<<EOB
  765. </tbody></table>
  766. </div><hr/>
  767. EOB;
  768. break;
  769. case5://itemdelete
  770. if(!isset($_GET['key'])||!isset($_GET['server'])){
  771. echo"Nokeyset!";
  772. break;
  773. }
  774. $theKey=htmlentities(base64_decode($_GET['key']));
  775. $theserver=$MEMCACHE_SERVERS[(int)$_GET['server']];
  776. list($h,$p)=explode(':',$theserver);
  777. $r=sendMemcacheCommand($h,$p,'delete'.$theKey);
  778. echo'Deleting'.$theKey.':'.$r;
  779. break;
  780. case6://flushserver
  781. $theserver=$MEMCACHE_SERVERS[(int)$_GET['server']];
  782. $r=flushServer($theserver);
  783. echo'Flush'.$theserver.":".$r;
  784. break;
  785. }
  786. echogetFooter();
  787. ?>

到此这篇关于基于Nginx的Mencached缓存配置详解的文章就介绍到这了,更多相关Nginx Mencached缓存配置内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.51cto.com/14832653/2506978

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 基于Nginx的Mencached缓存配置详解 https://www.kuaiidc.com/52827.html

相关文章

发表评论
暂无评论