memcache 操作类

浏览: 36 发布日期: 2016-10-05 分类: memcached

1.示例代码

<?php
namespace Common\Drive;

use \Memcache;

/**
 * Memcache 缓存操作类
 */
class Mcache 
{
    protected static $_instance = null;
    private $mcache;
    const CACHE_KEY     = 'userinfo';

    /**
     * Singleton instance
     *
     * @return Object
     */
    public static function getInstance($dbHost, $port)
    {
        if (self::$_instance === null) {
            self::$_instance = new self($dbHost, $port);
        }
        return self::$_instance;
    }

    /**
     * 链接Memcache缓存
     */
    public function __construct ($host='127.0.0.1', $port='11211')
    {
        if($this->mcache) return $this->mcache;
        $this->mcache = new Memcache();
        $this->mcache ->connect($host, $port);
    }

    /**
     * 获取key值
     * @param $key
     * @return mixed
     */
    public function get($keyssss)
    {
        $key = md5(static::CACHE_KEY.$keyssss);
        return $this->mcache->get($key);
    }


    /**
     * 设置key值
     * @param $key
     * @param $str
     * @return mixed
     */
    public function set($keyssss, $str, $time=60)
    {
        $key = md5(static::CACHE_KEY.$keyssss);
//        echo '设置'.$keyssss.'===='.$key.PHP_EOL;
        return $this->mcache->set($key, $str, 0, $time);
    }


    /**
     * 获取用户信息
     * @param $key
     * @return array|string
     */
    public function getUserInfo($key)
    {
        return $this->mcache->get($key);
    }

}
返回顶部