六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 857|回复: 0

多台memcache 研究-php-it论坛-计算机论坛

[复制链接]
 楼主| 发表于 2014-1-2 17:01:11 | 显示全部楼层 |阅读模式
多台memcache 研究-php-it论坛-计算机论坛
第一种方法是通过设置特殊key前缀实现分布,基本可以实现memcache和key的一对多关系,好处在于不会混淆,代码如下:
  1. <?php
  2. $key='en_key2';
  3. //print_r(mem_arr($key));
  4. $mem_arr=mem_arr($key);
  5. $mem = new Memcache;
  6. $mem->connect($mem_arr['host'],$mem_arr['port']);
  7. if(!$result=$mem->get('$key')){
  8.         $mem->set($key, 'This is a memcached test!', 0, 60);
  9.         $result=$mem->get($key);
  10.   }
  11. echo $result."---------".$mem_arr['host'].'--'.$mem_arr['port'];

  12. function mem_arr($key)
  13. {
  14.         $memcached = array(  

  15.         'cn'=>array('192.168.1.101',11212),

  16.         'en'=>array('192.168.1.102',11212)

  17.         );

  18.         if(substr($key,0,2)=='cn')
  19.         {
  20.                 $mem['host']=$memcached['cn'][0];
  21.                 $mem['port']=$memcached['cn'][1];
  22.         }else
  23.         {
  24.                 $mem['host']=$memcached['en'][0];
  25.                 $mem['port']=$memcached['en'][1];
  26.         }
  27.         return $mem;       
  28. }


  29. ------------在102上查看
  30. <?php
  31. $mem = new Memcache;
  32. $mem->connect("92.168.1.102", 11212);
  33. $val = $mem->get('en_key2');
  34. echo $val;

  35. ?>
复制代码
第二种方法是用的网上的一个方法,重写了memcache类,实现数组操作,这种方法对memcache服务器的扩展性不好
  1. MemcacheOpt.class.php

  2. <?php
  3. /**
  4. * Memcache 操作类 (支持同步和分组访问)
  5. * author     : heiyeluren <http://blog.csdn.net/heiyeshuwu>
  6. * created    : 2007-06-21
  7. * lastModifed: 2007-06-21
  8. */

  9. /** * Memcache操作类 */
  10. class MemcacheOpt
  11. {
  12.     //---------------------
  13.     //  属性定义
  14.     //---------------------
  15.     /**     * 是否进行多组同步      */
  16.     var $isGroup    = true;
  17.     /**
  18.      * 多组同步情况下是否使用减轻负载的随机存取
  19.      */
  20.     var $isRandom   = true;

  21.     /** 默认的Memcache服务器端口  */
  22.     var $mmcPort    = 11211;

  23.     /** 保存原始组信息*/
  24.     var $groups     = array();

  25.     /** 保存第一、二组Memcache服务器信息*/
  26.     var $group1     = array();
  27.     var $group2     = array();
  28.     /** * 保存第一、二组连接对象  */
  29.     var $mmc1       = '';
  30.     var $mmc2       = '';
  31.    

  32.     //---------------------
  33.     //   内部操作方法
  34.     //---------------------

  35.     /** 显示错误信息     *
  36.      * @param string $msg 需要显示消息的内容
  37.      * @param string $type 消息类型,error是普通错误消息,fatal 是致命错误,将终止程序执行, message 是普通消息,缺省状


  38.      * @return bool true
  39.      */
  40.     function showMessage($msg, $type){
  41.         $msg .= " ";
  42.         switch($type){
  43.             case 'error':
  44.                 echo("Memcache Error: ". $msg);
  45.                 break;
  46.             case 'fatal':
  47.                 die("Memcache Fatal: ". $msg);
  48.                 break;
  49.             case 'message':
  50.                 echo("Memcache Message: ". $msg);
  51.                 break;
  52.             default:
  53.                 echo("Memcache Error: ". $msg);
  54.         }
  55.         return true;
  56.     }


  57.     /**
  58.      * 构造函数 (初始化分组和连接到服务器)
  59.      */
  60.     function MemcacheOpt($hostArray, $hostArray2=array()){
  61.         if (!is_array($hostArray) || empty($hostArray)){
  62.             $this->showMessage('Memcache host list invalid', 'fatal');
  63.         }
  64.         $this->groups = array_merge($hostArray, $hostArray2);
  65.         $this->splitGroup($hostArray, $hostArray2);
  66.         $this->connect();
  67.     }

  68.     /**
  69.      * 对组进行切分 (按照是否需要分组进行相应的切分)
  70.      *
  71.      * @param array $hostArray 主机数组列表1
  72.      * @param array $hostArray2 主机数组列表2
  73.      * @return void
  74.      */
  75.     function splitGroup($hostArray, $hostArray2=array()){
  76.         //如果只有一台机器则不使用分组
  77.         if (count($hostArray) < 2 && empty($hostArray2)){  $this->isGroup = false;  }

  78.         //使用分组
  79.         if ($this->isGroup){
  80.             if (is_array($hostArray2) && !empty($hostArray2)){
  81.                 $this->group1 = $hostArray;
  82.                 $this->group2 = $hostArray2;
  83.             }else{
  84.                 $count = ceil(count($hostArray) / 2);
  85.                 $this->group1 = array_splice($hostArray, 0, $count);
  86.                 $this->group2 = array_splice($hostArray, 0);
  87.             }
  88.         }else{  $this->group1 = $hostArray;         }
  89.     }

  90.     /**     * 连接到Memcache服务器     */
  91.     function connect(){
  92.         if (!is_array($this->group1) || empty($this->group1)){
  93.             $this->showMessage("Memcache host1 array invalid", 'error');
  94.             return false;
  95.         }

  96.         //连接第一组Memcache服务器
  97.         $this->mmc1 = new Memcache;
  98.         foreach($this->group1 as $hosts){
  99.             $tmp = explode(":", $hosts);
  100.             $host = $tmp[0];
  101.             $port = (!isset($tmp[1]) || $tmp[1]=='') ? $this->mmcPort : $tmp[1];
  102.             $this->mmc1->addServer($host, $port);
  103.         }

  104.         //如果需要分组则连接第二组Memcache服务器
  105.         if ($this->isGroup){
  106.             if ( !is_array($this->group2) || empty($this->group2) ){
  107.                 $this->showMessage("Memcache host2 array invalid", 'error');
  108.                 return false;
  109.             }
  110.             $this->mmc2 = new Memcache;
  111.             foreach($this->group2 as $hosts){
  112.                 $tmp = explode(":", $hosts);
  113.                 $host = $tmp[0];
  114.                 $port = (!isset($tmp[1]) || $tmp[1]=='') ? $this->mmcPort : $tmp[1];
  115.                 $this->mmc2->addServer($host, $port);
  116.             }
  117.         }
  118.     }

  119.     /**     * 关闭Memcache服务器连接     */
  120.     function close(){
  121.         if (is_object($this->mmc1)){            $this->mmc1->close();        }
  122.         if (is_object($this->mmc1)){            $this->mmc1->close();        }        
  123.         return true;
  124.     }

  125.     /**
  126.      * 数据操作核心函数
  127.      *
  128.      * @param string $optType 操作类型,主要有 add, set, replace, delete, flush
  129.      * @param string $key 关键字,如果是 add,set,replace,delete 需要提交key参数
  130.      * @param string $val 关键字对应的值,如果是 add, set,replace 需要提交value参数
  131.      * @param int $expire 数据有效期,如果是 add,set,replace需要提交expire参数
  132.      * @return mixed 不同的需要产生不同的返回
  133.      */
  134.     function opt($optType, $key='', $val='', $expire=''){
  135.         if (!is_object($this->mmc1)){
  136.             $this->showMessage("Not availability memcache connection object", 'fatal');
  137.         }
  138.         if ($this->isGroup && !is_object($this->mmc2)){
  139.             $this->showMessage("Group 2 memcache host connection object not availability", 'error');
  140.         }

  141.         //加入数据操作
  142.         if ($optType=='add' || $optType=='set' || $optType=='replace'){
  143.             $this->mmc1->set($key, $val, false, $expire);
  144.             if ($this->isGroup && is_object($this->mmc2)){
  145.                 $this->mmc2->set($key, $val, false, $expire);
  146.             }
  147.             return true;
  148.         }

  149.         //获取数据操作
  150.         if ($optType == 'get'){

  151.             //缺省获取第一组数据
  152.             if (!$this->isGroup || !is_object($this->mmc2)){
  153.                 return $this->mmc1->get($key);        
  154.             }

  155.             //分组情况下逐组访问
  156.             $num = ( $this->isRandom ? rand(1, 2) : 1 );
  157.             $obj = "mmc". $num;
  158.             $val = $this->$obj->get($key);

  159.             //如果没有提取到数据,则访问另外一组
  160.             if ($val == ""){
  161.                 switch($num){
  162.                     case 1: $val = $this->mmc2->get($key); break;
  163.                     case 2: $val = $this->mmc1->get($key); break;
  164.                     default: $val = $this->mmc1->get($key);
  165.                 }
  166.             }
  167.             return $val;
  168.         }

  169.         //删除数据操作
  170.         if ($optType == 'delete'){
  171.             $this->mmc1->delete($key, $expire);
  172.             if ($this->isGroup && is_object($this->mmc2)){
  173.                 $this->mmc2->delete($key);        
  174.             }
  175.             return true;
  176.         }

  177.         //清空数据操作     
  178.         if($optType == 'flush'){
  179.             $this->mmc1->flush();
  180.             if ($this->isGroup && is_object($this->mmc2)){
  181.                 $this->mmc2->flush();        
  182.             }
  183.             return true;
  184.         }
  185.         
  186.     }
  187.     //---------------------
  188.     //   外部操作方法
  189.     //---------------------

  190.     //增加一个元素
  191.     function add($key, $val, $expire=''){   return $this->opt('add', $key, $val, $expire);     }

  192.     //增加一个元素
  193.     function set($key, $val, $expire=''){        return $this->opt('set', $key, $val, $expire);    }

  194.     //替换一个元素
  195.     function replace($key, $val, $expire=''){        return $this->opt('replace', $val, $expire);    }

  196.     //获取一个元素
  197.     function get($key){        return $this->opt('get', $key);    }

  198.     //删除一个元素
  199.     function delete($key, $timeout=''){      return $this->opt('delete', $key, '', $timeout);    }

  200.     //让所有的元素过期 (本接口不要轻易使用)
  201.     function flush(){       return $this->opt('flush');     }


  202.     /**     * 获取所有Memcache服务器状态     */
  203.     function getStats(){
  204.         $status = array();

  205.         //单独连接到每台Memcache
  206.         foreach($this->groups as $key=>$hosts){
  207.             $tmp = explode(":", $hosts);
  208.             $host = $tmp[0];
  209.             $port = (!isset($tmp[1]) || $tmp[1]=='') ? $this->mmcPort : $tmp[1];

  210.             $conn = new Memcache;
  211.             $conn->connect($host, $port);
  212.             $s = $conn->getStats();
  213.             $s['host'] = $host;
  214.             $s['port'] = $port;
  215.             $status[$key] = $s;
  216.         }
  217.         return $status;
  218.     }

  219.     /**
  220.      * 获取所有Memcache服务器版本号
  221.      */
  222.     function getVersion(){
  223.         $version = array();
  224.         $stats = $this->getStats();
  225.         foreach($stats as $key=>$s){
  226.             $v['host'] = $s['host'];
  227.             $v['port'] = $s['port'];
  228.             $v['version'] = $s['version'];
  229.             $version[$key] = $v;
  230.         }
  231.         return $version;
  232.     }

  233. }
  234. ?>

  235. 101:
  236. memcached -d -m 50 -p 11212 -u root
  237. memcached -d -m 50 -p 11213 -u root


  238. 102:
  239. memcached -d -m 50 -p 11212 -u root
  240. memcached -d -m 50 -p 11213 -u root

  241. <?php
  242. require_once("MemcacheOpt.class.php");

  243. //操作代码
  244. $hostArray = array("192.168.1.101:11212", "192.168.1.101:11213","192.168.1.102:11212","192.168.1.102:11213");
  245. $m = new MemcacheOpt($hostArray);

  246. $m->add("key1", "key1_value", 30);
  247. $m->add("key2", "key2_value", 30);
  248. $m->add("key3", "key3_value", 30);
  249. $m->add("key4", "key4_value", 30);
  250. echo $m->get("key1"). " ";
  251. echo $m->get("key2"). " ";
  252. echo $m->get("key3"). " ";
  253. echo $m->get("key4"). " ";
  254. print_r($m->getStats());
  255. print_r($m->getVersion());

  256. ?>
复制代码
今天测试还碰到一个奇怪的问题,下面三段代码都应该是可以执行的,最后一段却报错不能连接,不解。
  1. -----------ok
  2. <?php
  3. $mem = new Memcache;
  4. $mem->connect("127.0.0.1", 11211);
  5. $mem->set('key', 'This is a memcached test!', 0, 60);
  6. $val = $mem->get('key');
  7. echo $val;

  8. ?>


  9. --------ok
  10. 101:
  11. memcached -d -m 50 -p 11212 -u root
  12. memcached -d -m 50 -p 11213 -u root
  13. <?php
  14. $mem = new Memcache;
  15. $mem->connect("192.168.1.101",11212);
  16. $mem->set('keysss', 'This is a memcached test!', 0, 60);
  17. $val = $mem->get('keysss');
  18. echo $val;

  19. ?>

  20. ------------------------Warning: Memcache::connect() [memcache.connect]: Can't connect to 192.168.1.101:11211, Connection refused (111) in /var/www/mem3.php on line 3

  21. memcached启动的时候有一项是指定ip的,如果已经指定了IP.那么可能就无法再使用localhost或127.0.0.1(猜的,不知道是不是这样,俺一般是不指定的,所以默认localhost或127.0.0.1都是可以的)



  22. <?php
  23. $mem = new Memcache;
  24. $mem->connect("<strong><span style="color: #ff0000;">192.168.1.101",11211</span>);</strong>
  25. $mem->set('keysdf', 'This is a memcached test!', 0, 60);
  26. $val = $mem->get('keysdf');
  27. echo $val;

  28. ?>
复制代码
本文摘自:http://zhengdl126.iteye.com/blog/423779

该会员没有填写今日想说内容.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

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