ThinkPHP下面使用Memched

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

memcache.png

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

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

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服务器使用情况概览

步骤一:

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


                

Rejected!

Wrong Username or Password! 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 "
  • $title
  • "; } return "
  • $title
  • "; } function getHeader(){ $header = << MEMCACHE INFO

    phpmemcache.php by Harun Yayli


    EOB; return $header; } function getFooter(){ global $VERSION; $footer = '
    '; return $footer; } function getMenu(){ global $PHP_SELF; echo "

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

    ThinkPHP下面使用Memched_第1张图片
    aaa.png

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

    你可能感兴趣的:(ThinkPHP下面使用Memched)