热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

memcache通用类包括hash分配-PHP源码

memcache通用类包括hash分配

1. class.php

cOnfig= array(
            'host' => '127.0.0.1',
            'port' => 11211,
            'persistent' => false,
            'weight' => 1,
            //超时时间
            'timeout' => 1,
            //重试间隔时间
            'retry_interval' => 15,
            'status' => false,
            //=============================
            //是否打开压缩
            'threshold' => 1,
            //压缩率
            'min_savings' => 0.2,
            //最大重试次数
            'max_connect_retries' => 5
        );
        //不带一致性hash分配方案
        if (!isset($config['memcache_deploy']) || !is_callable($config['memcache_deploy'])) {
            $config['memcache_deploy'] = array(
                __CLASS__,
                'default_memcache_deploy'
            );
        }
        //带一致性hash分配方案
        if (!isset($config['memcache_hdeploy']) || !is_callable($config['memcache_hdeploy'])) {
            $config['memcache_hdeploy'] = array(
                __CLASS__,
                'default_memcache_hdeploy'
            );
        }
        //错误处理
        if (!isset($config['failure_callback']) || !is_callable($config['failure_callback'])) {
            $config['failure_callback'] = array(
                __CLASS__,
                'default_error_hander'
            );
        }
        $this->cOnfig= array_merge($this->config, $config);
        $this->memcache_obj = new \Memcache;
    }
    public function host($host_list = '')
    {
        $this->host_list = $host_list;
        return $this;
    }
    //默认错误处理
    static public function default_error_hander($host = array())
    //var_dump($host);
    {
         
    }
    static public function default_memcache_hdeploy($host, $hash = '')
    {
        static $node_object;
        if (!($node_object instanceof yhash)) {
            $cOnfig= array(
                //虚拟节点20个
                'replicas' => 20
            );
            $node_object = new yhash($config);
            //添加节点
            $node_object->addTargets(array_keys($host));
        }
        return $node_object->lookup($hash);
    }
     
     
    static public function default_memcache_deploy($host)
    {
        $keys = array_keys($host);
        $key  = array_rand($keys, 1);
        return $keys[$key];
    }
     
    public function alink()
    {
         
        $default_host     = array(
            'host' => $this->config['host'],
            'port' => $this->config['port'],
            'persistent' => $this->config['persistent'],
            'weight' => $this->config['weight'],
            'timeout' => $this->config['timeout'],
            'retry_interval' => $this->config['retry_interval'],
            'status' => $this->config['status'],
            'failure_callback' => $this->config['failure_callback'],
            'threshold' => $this->config['threshold'],
            'min_savings' => $this->config['min_savings']
        );
        $failure_callback = '';
        if (!empty($this->host_list)) {
            foreach ($this->host_list as $_host) {
                $_host = array_merge($default_host, $_host);
                $failure_callback = function($host = '', $port = 11211) use ($_host)
                {
                    return call_user_func_array($_host['failure_callback'], array(
                        $_host
                    ));
                };
                $this->memcache_obj->addServer($_host['host'], $_host['port'], $_host['persistent'], $_host['weight'], $_host['timeout'], $_host['retry_interval'], $_host['status'], $failure_callback);
                if ($_host['threshold']) {
                    $this->memcache_obj->setCompressThreshold($_host['threshold'], $_host['min_savings']);
                }
            }
        } else {
            $failure_callback = function($host = '', $port = 11211) use ($default_host)
            {
                return call_user_func_array($default_host['failure_callback'], array(
                    $default_host
                ));
            };
            $this->memcache_obj->addServer($default_host['host'], $default_host['port'], $default_host['persistent'], $default_host['weight'], $default_host['timeout'], $default_host['retry_interval'], $default_host['status'], $failure_callback);
            if ($default_host['threshold']) {
                $this->memcache_obj->setCompressThreshold($default_host['threshold'], $default_host['min_savings']);
            }
             
        }
    }
     
    public function link()
    {
        $default_host = '';
        $host_no      = -1;
        $return       = false;
        $_host        = array();
        if (!empty($this->host_list)) {
            $host_no = call_user_func_array($this->config['memcache_deploy'], array(
                $this->host_list
            ));
            $_host   = $this->host_list[$host_no];
        }
         
        $default_host = array(
            'host' => $this->config['host'],
            'port' => $this->config['port'],
            'persistent' => $this->config['persistent'],
            //'weight'=>$this->config['weight'],
            'timeout' => $this->config['timeout'],
            'retry_interval' => $this->config['retry_interval'],
            //'status'=>$this->config['status'],
            'failure_callback' => $this->config['failure_callback'],
            'threshold' => $this->config['threshold'],
            'min_savings' => $this->config['min_savings']
        );
        $_host        = array_merge($default_host, $_host);
         
        if ($_host['persistent']) {
            $return = @$this->memcache_obj->pconnect($_host['host'], $_host['port'], $_host['timeout']);
        } else {
            $return = @$this->memcache_obj->connect($_host['host'], $_host['port'], $_host['timeout']);
        }
        if (!$return) {
            $this->connectFailures++;
            if ($this->connectFailures <= $this->config[&#39;max_connect_retries&#39;]) {
                if (count($this->host_list) > 1) {
                    call_user_func_array($_host[&#39;failure_callback&#39;], array(
                        $_host
                    ));
                    usleep($_host[&#39;interval_time&#39;]);
                    unset($this->host_list[$host_no]);
                    $this->link();
                } else {
                    $this->cOnnectFailures= 0;
                    call_user_func_array($_host[&#39;failure_callback&#39;], array(
                        $_host
                    ));
                }
            } else {
                $this->cOnnectFailures= 0;
                call_user_func_array($_host[&#39;failure_callback&#39;], array(
                    $_host
                ));
            }
        } else {
            $this->cOnnectFailures= 0;
            if ($_host[&#39;threshold&#39;]) {
                $this->memcache_obj->setCompressThreshold($_host[&#39;threshold&#39;], $_host[&#39;min_savings&#39;]);
            }
             
        }
    }
     
     
     
    public function hlink($hash = &#39;&#39;)
    {
         
        $default_host = &#39;&#39;;
        $host_no      = -1;
        $return       = false;
        $_host        = array();
        if (!empty($this->host_list)) {
            $host_no = call_user_func_array($this->config[&#39;memcache_hdeploy&#39;], array(
                $this->host_list,
                $hash
            ));
            $_host   = $this->host_list[$host_no];
        }
         
        $default_host = array(
            &#39;host&#39; => $this->config[&#39;host&#39;],
            &#39;port&#39; => $this->config[&#39;port&#39;],
            &#39;persistent&#39; => $this->config[&#39;persistent&#39;],
            //&#39;weight&#39;=>$this->config[&#39;weight&#39;],
            &#39;timeout&#39; => $this->config[&#39;timeout&#39;],
            &#39;retry_interval&#39; => $this->config[&#39;retry_interval&#39;],
            //&#39;status&#39;=>$this->config[&#39;status&#39;],
            &#39;failure_callback&#39; => $this->config[&#39;failure_callback&#39;],
            &#39;threshold&#39; => $this->config[&#39;threshold&#39;],
            &#39;min_savings&#39; => $this->config[&#39;min_savings&#39;],
            &#39;hash&#39; => $hash
        );
        $_host        = array_merge($default_host, $_host);
        if ($_host[&#39;persistent&#39;]) {
            $return = $this->memcache_obj->pconnect($_host[&#39;host&#39;], $_host[&#39;port&#39;], $_host[&#39;timeout&#39;]);
        } else {
            $return = $this->memcache_obj->connect($_host[&#39;host&#39;], $_host[&#39;port&#39;], $_host[&#39;timeout&#39;]);
        }
        if (!$return) {
             
            $this->cOnnectFailures= 0;
            call_user_func_array($_host[&#39;failure_callback&#39;], array(
                $_host
            ));
             
        } else {
             
            if ($_host[&#39;threshold&#39;]) {
                $this->memcache_obj->setCompressThreshold($_host[&#39;threshold&#39;], $_host[&#39;min_savings&#39;]);
            }
             
        }
    }
    /*
    type类型 值reset, malloc, maps, cachedump, slabs, items, sizes
    slabid slab的id
    limit 返回的最大条数
    */
    public function _server($type = &#39;&#39;, $slabid = 1, $limit = 1000000)
    {
        //$this->memcache_obj->close();
        if ($type === &#39;&#39;)
            return $this->memcache_obj->getStats();
        if ($type != &#39;cachedump&#39;)
            return $this->memcache_obj->getStats($type);
        return $this->memcache_obj->getStats($type, $slabid, $limit);
    }
    public function _allserver($type = &#39;&#39;, $slabid = 1, $limit = 1000000)
    {
        if ($type === &#39;&#39;)
            return $this->memcache_obj->getExtendedStats();
        if ($type != &#39;cachedump&#39;)
            return $this->memcache_obj->getExtendedStats($type);
        return $this->memcache_obj->getExtendedStats($type, $slabid, $limit);
    }
    public function close()
    {
        return $this->memcache_obj->close();
    }
    public function slabid()
    {
        $ids = $id = array();
        $ids = $this->memcache_obj->getStats(&#39;slabs&#39;);
        foreach ($ids as $k => $v) {
            if (is_int($k)) {
                $id[] = $k;
            }
        }
        return $id;
    }
    //!!!!!!!!!!!============================================
    public function getallkey($limit = 1000000)
    {
        $ids = $this->slabid();
        $arr = array();
        foreach ($ids as $id) {
            $arr = array_merge(array_keys($this->memcache_obj->getStats(&#39;cachedump&#39;, $id, $limit)), $arr);
        }
        return $arr;
    }
    public function set($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
    {
        return $this->memcache_obj->set($key, $var, $flag, $expire);
    }
     
    public function add($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
    {
        return $this->memcache_obj->add($key, $var, $flag, $expire);
    }
     
    public function get($key, &$flag = 0)
    {
        $gflag  = 0;
        $return = $this->memcache_obj->get($key, $gflag);
        $flag   = $gflag;
        return $return;
    }
     
    public function delete($key, $timeout = 0)
    {
        if ($key === &#39;all&#39;) {
            return $this->memcache_obj->flush();
        }
        return $this->memcache_obj->delete($key, $timeout);
    }
    public function replace($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
    {
        return $this->memcache_obj->replace($key, $var, $flag, $expire);
    }
     
    public function increment($key, $var)
    {
        return $this->memcache_obj->increment($key, (int) $var);
    }
     
    public function decrement($key, $var)
    {
        return $this->memcache_obj->decrement($key, (int) $var);
    }
     
    public function append($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
    {
        $return = $this->memcache_obj->get($key);
        if (empty($return))
            return false;
        return $this->memcache_obj->replace($key, $return . $var, $flag, $expire);
    }
    public function prepend($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
    {
        $return = $this->memcache_obj->get($key);
        if (empty($return))
            return false;
        return $this->memcache_obj->replace($key, $var . $return, $flag, $expire);
    }
    public function cas($key, $key2)
    {
        $return1 = $this->memcache_obj->get($key);
        if (empty($return1))
            return false;
        $return2 = $this->memcache_obj->get($key2);
        if (empty($return2))
            return false;
        return ($this->memcache_obj->replace($key, $return2)) && ($this->memcache_obj->replace($key2, $return));
    }
 }

2. memcache.php

 
 &#39;127.0.0.1&#39;,
    //端口
    &#39;port&#39; => 11211,
    //是否长连接
    &#39;persistent&#39; => false,
    //比重
    &#39;weight&#39; => 1,
    //超时时间
    &#39;timeout&#39; => 1,
    //重试间隔时间
    &#39;retry_interval&#39; => 15,
    //状态
    &#39;status&#39; => false,
    //=============================
    //是否打开压缩
    &#39;threshold&#39; => 1,
    //压缩率
    &#39;min_savings&#39; => 0.2,
    //最大重试次数
    &#39;max_connect_retries&#39; => 5,
    //不带一致性hash分配方案
    //回调函数
    //参数 主机数组
    &#39;memcache_deploy&#39; => &#39;default_memcache_deploy&#39;,
    //带一致性hash分配方案
    //回调函数
    //参数 主机数组 hash值
    &#39;memcache_hdeploy&#39; => &#39;default_memcache_hdeploy&#39;,
    //错误处理
    //回调函数
    //参数 主机数组
    &#39;failure_callback&#39; => &#39;default_error_hander&#39;
);
//====================================================================================
//连接
/*memcahe 三种连接方式
1.连接池addserver
2.普通connect/pconnect
3.带hash的connect/pconnect
*/
//1.连接池
$memcache = new memcache();
$host     = array(
    array(
        &#39;host&#39; => &#39;localhost&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;localhost&#39;,
        &#39;port&#39; => &#39;11212&#39;
    ),
    array(
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => &#39;11212&#39;
    )
);
$memcache->host($host);
$memcache->alink();
//print_r($memcache->_allserver());
//-------------------------------------------------------------
//2.普通connect/pconnect
$memcache2 = new memcache();
$host      = array(
    array(
        &#39;host&#39; => &#39;localhost&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;localhost&#39;,
        &#39;port&#39; => &#39;11212&#39;
    ),
    array(
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => &#39;11212&#39;
    )
);
$memcache2->host($host);
$memcache2->link();
//print_r($memcache2->_allserver());
//--------------------------------------------------------------
//3.带hash的connect/pconnect
//导入算法类
include(&#39;../lib/hash/class.php&#39;);
$memcache3 = new memcache();
$host      = array(
    array(
        &#39;host&#39; => &#39;localhost&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;localhost&#39;,
        &#39;port&#39; => &#39;11211&#39;
    ),
    array(
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => &#39;11211&#39;
    )
);
$memcache3->host($host);
//$memcache3->hlink(&#39;233ybl&#39;);
//print_r($memcache3->_allserver());
//==================================================================================
//内置函数
//set($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
//add($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
//get($key, &$flag = 0)
//delete($key, $timeout = 0)
//replace($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
//increment($key, $var)
//decrement($key, $var)
//append($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
//prepend($key, $var, $expire = 0, $flag = MEMCACHE_COMPRESSED)
// cas($key, $key2)
$memcache3->hlink(&#39;32ybl&#39;);
$memcache3->set(&#39;32ybl&#39;, 55);
//$memcache3->increment(&#39;32ybl&#39;,333);
echo $memcache3->get(&#39;32ybl&#39;);
//======================================================================
//系统函数
//获取当前连接服务器信息
//_server($type = &#39;&#39;, $slabid = 1, $limit = 1000000)
//获取所有连接服务器信息
//_allserver($type = &#39;&#39;, $slabid = 1, $limit = 1000000)
//获取所有key名
//getallkey($limit=1000000)
var_dump($memcache->getallkey());

推荐阅读
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • Linux服务器密码过期策略、登录次数限制、私钥登录等配置方法
    本文介绍了在Linux服务器上进行密码过期策略、登录次数限制、私钥登录等配置的方法。通过修改配置文件中的参数,可以设置密码的有效期、最小间隔时间、最小长度,并在密码过期前进行提示。同时还介绍了如何进行公钥登录和修改默认账户用户名的操作。详细步骤和注意事项可参考本文内容。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
  • 本文介绍了游戏开发中的人工智能技术,包括定性行为和非定性行为的分类。定性行为是指特定且可预测的行为,而非定性行为则具有一定程度的不确定性。其中,追逐算法是定性行为的具体实例。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • 关于我们EMQ是一家全球领先的开源物联网基础设施软件供应商,服务新产业周期的IoT&5G、边缘计算与云计算市场,交付全球领先的开源物联网消息服务器和流处理数据 ... [详细]
author-avatar
echo7111436
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有