设为首页 收藏本站
查看: 1200|回复: 0

[经验分享] memcache运用代码

[复制链接]

尚未签到

发表于 2017-4-14 12:59:43 | 显示全部楼层 |阅读模式
  interface ICache {

    public function put($key,$var,$timeout=0);

    public function get($key);

    public function delete($key);

    public function close();

    public function open($params);

}









class FileCache{

   private $filecache_path;
  /**
     * 構造函數
     * @param String $file DbFlat文件名,不存在將創建
     * @param Int $mode DbFlat文件的讀寫模式
     * @param Int $perm DbFlat文件權限
     */
    function __construct($filePath){
        if(file_exists($filePath)){
            $this->filecache_path = $filePath;
        }else{
            $this->make_dir($filePath);
            $this->filecache_path = $filePath;
        }
    }
  
   /**
     * 存儲一個Key
     * @param String $key Key
     * @param String $val Value
     * @return Boolean
     */
    function store($key,$val){
         $files = $this->filecache_path."/{$key}_filecache";
         return file_put_contents($files, serialize($val));
    }
   
    /**
     * 獲得指定Key的值
     * @param String $key Key
     * @return String
     */
    public function fetch($key){
        $files = $this->filecache_path."/{$key}_filecache";
        if(file_exists($files)){
            $str = file_get_contents($files);
            if($str === false || $str === '') {
                return null;
            }
            else{
                 return unserialize($str);
            }
        }
    }
   
  /**
     * 刪除一個Key
     * @param String $key Key
     * @return Boolean
     */
    public function delete($key){
        $files = $this->filecache_path."/{$key}_filecache";
        if(file_exists($files)){
            unlink($files);
        }
    }
   
    /**
     * 刪除一個數組里的所以Key
     * @param Array $key_array
     * @return void
     */
    public function delete_array($key_array){
        foreach($key_array as $key){
            $this->delete($key);
        }
    }
   
    /**
     * 遞迴生成文件夾
     * @param str $path 文件夾path, 不是文件的path
     * @return mixed 成功時返回創建成功的path,失敗時返回false
     */
    public function make_dir($path)
    {
        if(! file_exists($path))
        {
            $this->make_dir(dirname($path));
            mkdir($path, 0777);
        }
        return realpath($path);
    }
}






require_once('ICache.iface.php');

class ApcCache implements ICache {
    public function put($key,$var,$timeout=0) {
        $succ = true;//apc_store($key,$var,$timeout);
        return $succ;
    }
   
    public function get($key) {
//echo "<hr>get==$key==from apc ==<hr>";
        //return apc_fetch($key);
        return '';
    }

    public function delete($key) {
        //return apc_delete($key);
        return '';
    }

    public function close() {    }

    public function open($params) {    }

}




require_once('ICache.iface.php');

class MemCached implements ICache {
    //实例化memcache对象
    public  $mc = null;
   
    /**
     * 构造实例化
     * $config_array:memcache服务器IP和端口
     *@return  obj
     */
    public function __construct($config_array){
        //服务器端调用方式
        $this->mc = new Memcache;
        //$mc->connect($memcache_url, 11212);   #[单一服务器可用]
        if (is_array($config_array)) {
            foreach ($config_array as $key=>$value){
                $this->mc->addServer($value['IP'], $value['port']);
            }
        }
        $this->mc->setCompressThreshold(10240, 0.2);
  /*
  $this->mc->setCompressThreshold(10240, 0.2);  此函数在memcache2.0.0加入。
Memcache::setCompressThreshold()开启对于大值的自动压缩。 同样你也可以使用函数memcache_set_compress_threshold()。
参数一:控制多大值进行自动压缩的阈值。
参数二:指定经过压缩实际存储的值的压缩率,支持的值必须在0和1之间。默认值是0.2表示20%压缩率。

$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);
  */
    }
   
    /**
     * 值加入到memcache
     * $key:标识
     * $var:值
     * $timeout:失效时间 默认时间86400表示为一天时间。
     *@return  true or false
     */
    public function put($key,$var,$timeout=86400,$is_compress=0) {
        $succ = $this->mc->set($key,$var,$is_compress,$timeout);
        if($succ === false){
            //如果失败,休息一秒钟,则继续重写
            sleep(1);
            $succ = $this->mc->set($key,$var,$is_compress,$timeout);
            if($succ  === false ){
                log_error('set memache key failed!! key:'.$key.' value:'.serialize($var).' timeout:'.$timeout, __FILE__, __LINE__); 
            }
        }
        return $succ;
    }
   
    /**
     * 根据key值从memcache得到值
     * $key:标识
     *@return  string or array
     */
    public function get($key) {
        $result = $this->mc->get($key);
        if($result === false && (is_string($key) && strpos($key,'online') === false)){
            //log_error('get memache key ('.$key.') failed!!', __FILE__, __LINE__);
        }
        return $result;
    }
   
    /**
     * 根据key值从memcache删除值
     * $key:标识
     *@return  true or false
     */
    public function delete($key) {
        $succ = $this->mc->delete($key);
        if($succ === false){
            //如果失败,休息一秒钟,则继续删除
            sleep(1);
            $succ = $this->mc->delete($key);
            //if($succ === false){
            //    log_error('delete memache key('.$key.') failed!!',__FILE__,__LINE__);
            //}
        }
        return $succ;
    }

    /**
     * 关键memcache
     *@return  true or false
     */
    public function close(){
        return $this->mc->close();
    }
   
    public function open($params) {    }

}






require_once('ICache.iface.php');
require_once('LocalCache.class.php');

class CacheStore{
    private $_caches;
    private $_storeName;
    private $_defaultCache;
   
    public function setName($name){
        $this->_storeName = $name;
    }
   
    public function setCache(ICache $cache, $privilege=0){
        $this->_caches[$privilege] = $cache;
    }
   
    public function getCache($privilege=0){
        return $this->_caches[$privilege];   
    }

    public function init(){
        //if(!is_array($this->_caches)){
        $this->setCache(new LocalCache());
        //}
        ksort($this->_caches);
       
    }
   
    public function put($key, $value, $privilege=-1){
       
    if($privilege == 0){ //指定赋值给默认的
            $this->_caches[0]->put($this->_storeName . '_' . $key, $value);
        }else{
            foreach($this->_caches as $cache){
                $cache->put($this->_storeName . '_' . $key, $value);
            }
        }

    }
   
    public function get($key){
        $i = 0;
        foreach($this->_caches as $cache){
            $val = null;
            $val = $cache->get($this->_storeName . '_' . $key);
            if($val!=null){
                if($i > 0){
                    $this->put($key,$val,0);
                }
                return $val;
            }
            $i++;
        }
        return $val;
    }
}






$arr_server_memcache = array(
    array(
        'IP' => '192.168.101.73',
        'port' => '12000'
    ),
    array(
        'IP' => '192.168.101.74',
        'port' => '12000'
    ),
    array(
        'IP' => '192.168.101.75',
        'port' => '12000'
    ),
    array(
        'IP' => '192.168.101.76',
        'port' => '12000'
    ),
    array(
        'IP' => '192.168.101.77',
        'port' => '12000'
    )
);


require('pworks/util/cache/CacheStore.class.php');
require_once('pworks/util/cache/ApcCache.class.php');
require_once('pworks/util/cache/MemCache.class.php');


$appCache = new CacheStore();
    $appCache->setName(MARKSIX_SYSTEM.'_mvc_app_obj');
    //$appCache->setCache(new ApcCache());
    //加入memcached缓存
    if (MEMCACHE) {
        $appCache->setCache(new MemCached($arr_server_memcache), 'mc');
    }
    $appCache->init();
  /**
     * 得到memcache实例
     */
    function memc(){
        return FrontController::getCache('mc');
    }
  /**
     * 得到memcache里存放当前用户标识的key
     */
    function get_mem_key(){
        return COM_TYPE == 'f' ? get_online_member_key($_SESSION['memberId']) : get_online_user_key($_SESSION['userId']);
    }

    /**
     * 给memcache里存放当前用户标识的key赋值当前的session,EXPIRE_TIME默认为 10
     */
    function set_mem_key(){
        returnmemc()->put(get_mem_key(), get_new_session_id(get_session_id()), EXPIRE_TIME);
    }

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-364926-1-1.html 上篇帖子: 漫谈 memcache (一) 下篇帖子: memcache for python
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表