• memcache通过hash取模算法,实现多服务器存取值


    <?php
    //封装一个hash算法类
    class Mem{
        //存储memcache的服务器个数
        private $hostCount='';
        //多个服务器
        private $host=[];
    
        //构造方法用来给接收值,给属性赋值
        public function __construct($hostServer)
        {
            $this->hostCount = count($hostServer);
            $this->host = $hostServer;
        }
    
        //计算key的位置,返回的是当前是第几台服务器
        public function position($key){
            echo sprintf('%u',crc32($key))%$this->hostCount;//取余数
            return sprintf('%u',crc32($key))%$this->hostCount;
        }
    
        //根据取到的位置获取当前memcache对象,链接memcache
        public function getMemObj($position){
            //在服务器池中获取某一台的地址和端口号
            $host=$this->host[$position]['host'];
            $port=$this->host[$position]['port'];
            $MemObj = new Memcache();
            $MemObj->addServer($host,$port);
            return $MemObj;
        }
    
        //设置值
        public function SetData($key,$value){
            //找到服务器位置
            $num = $this->position($key);
            //连接服务器
            $m = $this->getMemObj($num);
            return $m->set($key,$value);
        }
    
        public function GetData($key){
            //找到服务器位置
            $num = $this->position($key);
            //连接服务器
            $m = $this->getMemObj($num);
            return $m->get($key);
    
        }
    }
    
    $host = [
        [
            'host'=>'127.0.0.1',
            'port'=>'11211'
        ],
        [
            'host'=>'127.0.0.2',
            'port'=>'11212'
        ]
    ];
    $obj = new Mem($host);
    $obj->position('sex');
    通往牛逼的路上,在意的只有远方!
  • 相关阅读:
    [ext4]空间管理
    [ext4] 磁盘布局
    [ext4]磁盘布局
    [ext4]08 磁盘布局
    [ext4]07 磁盘布局
    [ext4]06 磁盘布局
    [ext4]05 磁盘布局
    jQuery之链式编程
    jQuery之排他思想
    jQuery之筛选方法
  • 原文地址:https://www.cnblogs.com/jiangshiguo/p/9826138.html
Copyright © 2020-2023  润新知