ThinkPHP下面使用Memched

1.查看Linux服务器是否已经安装memcache和memecached是否已经安装

memcache.png

如果没安装请安装,此处省略安装步骤。如果已经安装请往下...

2.查看框架是否已经有memecached驱动类,如果没有请参照此类:

<?php

namespace Think\Cache\Driver;
use Think\Cache;
defined('THINK_PATH') or exit();
/**
 * Memcached缓存驱动
 */
Class Memcached extends Cache {

    public function __construct($options = array()) {
        if (!extension_loaded('memcached')) {
            throw_exception(L('_NOT_SUPPERT_') . ':memcached');
        }
        $servers = array();
        $persistent_id = C('PERSISTENTID') ? C('PERSISTENTID') : null;

        $this->options = $options;
        $this->options['expire'] = isset($options['expire']) ? $options['expire'] : C('DATA_CACHE_TIME');
        $this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : C('DATA_CACHE_PREFIX');
        $host = C('MEMCACHED_HOST') ? C('MEMCACHED_HOST') : '127.0.0.1';
        $port = C('MEMCACHED_PORT') ? C('MEMCACHED_PORT') : 11211;
        $weight = C('MEMECACHED_WEIGHT') ? C('MEMECACHED_WEIGHT') : 1;
        $weight_is_arr = is_array($weight);


        if (is_array($host)) {
            if (!is_array($port)) {
                throw_exception('Memcached服务器IP和端口号要一一对应');
            }
            if ($weight_is_arr && count($weight) != count($host)) {
                throw_exception('Memcached服务器IP和权重值要一一对应');
            }
            foreach ($host as $key => $value) {
                $servers[] = array($value, $port[$key], $weight_is_arr ? $weight[$key] : $weight);
            }
        } else {
            if (is_array($port)) {
                foreach ($port as $key => $value) {
                    $servers[] = array($host, $value, $weight_is_arr ? $weight[$key] : $weight);
                }
            } else {
                $servers[] = array($host, $port, $weight_is_arr ? $weight[0] : $weight);
            }
        }
        $this->handler = new \Memcached($persistent_id);
        $this->handler->addServers($servers);
//        $serverList = $this->handler->getServerList();
//        var_dump($serverList);
//        var_dump($this->handler->getStats());
//        var_dump($this->handler->getOption());
//        var_dump($this->handler->getVersion());
// p($serverList);
    }

    /**
     * 读取缓存
     * @access public
     * @param string $name 缓存变量名
     * @return mixed
     */
    public function get($name) {
        N('cache_read', 1);
        return $this->handler->get($this->options['prefix'] . $name);
    }

    /**
     * 读取多个元素值
     * @param  array  $keys [要读取的元素key数组]
     * @return [boolean]       [返回值]
     */
    public function getMulti($keys = array()) {
        if (empty($keys))
            return '';
        N('cache_read', 1);
        return $this->handler->getMulti($keys);
    }

    /**
     * 写入缓存
     * @access public
     * @param string $name 缓存变量名
     * @param mixed $value  存储数据
     * @param integer $expire  有效时间(秒)
     * @return boolen
     */
    public function set($name, $value, $expire = 0) {
        N('cache_write', 1);
        if (is_null($expire)) {
            $expire = $this->options['expire'];
        }
        $name = $this->options['prefix'] . $name;
        if ($this->handler->set($name, $value, $expire)) {
            return true;
        }
        return false;
    }

    /**
     * 写入多个元素
     * @param [array] $items  [要写入的健/值元素数组]
     * @param [int] $expire [有效时间(秒)]
     */
    public function setMulti($items, $expire = 0) {
        N('cache_write', 1);
        if (is_null($expire)) {
            $expire = $this->options['expire'];
        }
        $name = $this->options['prefix'] . $name;

        if ($this->handler->setMulti($items, $expire)) {
            return true;
        }
        return false;
    }

    /**
     * 添加一个元素,如果这个元素已经存在,则失败
     * @param [string]  $key    [要添加元素的key]
     * @param [string]  $value  [要添加元素的值]
     * @param integer $expire [有效时间]
     * @return boolean
     */
    public function add($key, $value, $expire = 0) {
        N('cache_write', 1);
        return $this->handler->add($key, $value, $expire);
    }

    /**
     * 替换已存在key下的元素,如果不存在此key则失败
     * @param  [string]  $key    [要替换的key]
     * @param  [string]  $value  [要替换的值]
     * @param  integer $expire [有效时间]
     * @return [boolean]          
     */
    public function replace($key, $value, $expire = 0) {
        N('cache_write', 1);
        return $this->handler->replace($key, $value, $expire);
    }

    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolen
     */
    public function rm($name) {
        $name = $this->options['prefix'] . $name;
        return $this->handler->delete($name);
    }

    /**
     * 清除缓存
     * @access public
     * @return boolen
     */
    public function clear() {
        return $this->handler->flush();
    }

}

把此类直接放在

/ThinkPHP/Library/Think/Cache/Driver 此处即可。

3.在框架的配置文件中配置

    //MEMCACHED缓存
    'DATA_CACHE_TYPE' => 'Memcached',
    'MEMCACHED_HOST' => '127.0.0.1', 
    'MEMCACHED_PORT' => '11211', 

4.在控制器中测试调试调用

namespace Api\Controller;
use Think\Memcached;
class IndexController extends Controller {
    /**
     * 控制器初始化
     */
    private $Memcached;
    public function __construct()
    {   
        parent::__construct();
        $this->Memcached = new \Memcached();
        $this-> Memcached->addServer('127.0.0.1', 11211);
    }
     //测试memcached
    //示列,并非一定要使用该代码测试!
    public function index()   
    {   
        //先判断缓存存不存在,如果不存在那就先获取数据再设置缓存
        $list = array(
            'id' => '1',
            'name' => '张三',
            'sex' => '女',
            'age' =>'18'
        );
        if(!$list = $this->Memcached->get('Index_')){
            /*参数
            * 缓存的名称
            * 缓存的数据
            * 缓存的时间
            */
            $this->Memcached->set('Index_',$list,10);
        }   
        echo json_decode($list);
    }
}

以上测试如果有结果说明你已经成功使用memcached缓存

4.监控memcached服务器使用情况概览

<h6>步骤一:

1.把该代码文件存放于项目根目录

<?php
//测试
$VERSION='$Id: memcache.php,v 1.1.2.3 2008/08/28 18:07:54 mikl Exp $';

define('ADMIN_USERNAME','memcached');   // Admin Username
define('ADMIN_PASSWORD','123456');      // Admin Password
define('DATE_FORMAT','Y/m/d H:i:s');
define('GRAPH_SIZE',200);
define('MAX_ITEM_DUMP',50);

$MEMCACHE_SERVERS[] = '127.0.0.1:11211'; // add more as an array


////////// 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">memcache</a></span>
        <span class="nameinfo">phpmemcache.php by <a href="http://livebookmark.net">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']}">Refresh Data</a></li>
EOB;
}
else {
echo <<<EOB
    <li><a href="$PHP_SELF&op=2}">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++.'">'.$server.'</a><br/>';
            }
        }
        else{
            echo '1.'.$MEMCACHE_SERVERS[0];
        }
        if (isset($_GET['singleout'])){
              echo '<a href="'.$PHP_SELF.'">(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">[<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,'">',$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).'">',$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),"\">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();

?>

然后访问该文件如:http://xxxxx.com/phpmemcache.php

aaa.png

如果你能看见说明你已经成功了。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 1、memcache的概念? Memcache是一个高性能的分布式的内存对象缓存系统,通过在内存里维护一个统一的巨...
    桖辶殇阅读 2,138评论 2 12
  • 转载地址:http://gnucto.blog.51cto.com/3391516/998509 Redis与Me...
    Ddaidai阅读 21,400评论 0 82
  • 一致性Hash算法 从上面的图中,可以看出一个很重要的问题,就是对服务器集群的管理,路由算法至关重要,就和负载均衡...
    青晨点支烟阅读 1,917评论 0 6
  • “嗨,处女座你去好好爱你的金牛座吧!好好的幸福着走下去吧!被你喜欢的人都会很幸运的,我会真心的祝福你。如果突然有一...
    于湙远阅读 597评论 0 2