• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
车车大人
博客园    首页    新随笔    联系   管理     

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');

 

通往牛逼的路上,在意的只有远方!
posted @ 2018-10-21 18:27  车车大人  阅读(470)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3