李斯特 发表于 2017-4-14 12:46:09

多台memcache 研究

  第一种方法是通过设置特殊key前缀实现分布,基本可以实现memcache和key的一对多关系,好处在于不会混淆,代码如下:

<?php
$key='en_key2';
//print_r(mem_arr($key));
$mem_arr=mem_arr($key);
$mem = new Memcache;
$mem->connect($mem_arr['host'],$mem_arr['port']);
if(!$result=$mem->get('$key')){
$mem->set($key, 'This is a memcached test!', 0, 60);
$result=$mem->get($key);
}
echo $result."---------".$mem_arr['host'].'--'.$mem_arr['port'];
function mem_arr($key)
{
$memcached = array(
'cn'=>array('192.168.1.101',11212),
'en'=>array('192.168.1.102',11212)
);
if(substr($key,0,2)=='cn')
{
$mem['host']=$memcached['cn'];
$mem['port']=$memcached['cn'];
}else
{
$mem['host']=$memcached['en'];
$mem['port']=$memcached['en'];
}
return $mem;
}

------------在102上查看
<?php
$mem = new Memcache;
$mem->connect("92.168.1.102", 11212);
$val = $mem->get('en_key2');
echo $val;
?>
  第二种方法是用的网上的一个方法,重写了memcache类,实现数组操作,这种方法对memcache服务器的扩展性不好

MemcacheOpt.class.php
<?php
/**
* Memcache 操作类 (支持同步和分组访问)
* author   : heiyeluren <http://blog.csdn.net/heiyeshuwu>
* created    : 2007-06-21
* lastModifed: 2007-06-21
*/
/** * Memcache操作类 */
class MemcacheOpt
{
//---------------------
//属性定义
//---------------------
/**   * 是否进行多组同步      */
var $isGroup    = true;
/**
* 多组同步情况下是否使用减轻负载的随机存取
*/
var $isRandom   = true;
/** 默认的Memcache服务器端口*/
var $mmcPort    = 11211;
/** 保存原始组信息*/
var $groups   = array();
/** 保存第一、二组Memcache服务器信息*/
var $group1   = array();
var $group2   = array();
/** * 保存第一、二组连接对象*/
var $mmc1       = '';
var $mmc2       = '';

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

* @return bool true
*/
function showMessage($msg, $type){
$msg .= " ";
switch($type){
case 'error':
echo("Memcache Error: ". $msg);
break;
case 'fatal':
die("Memcache Fatal: ". $msg);
break;
case 'message':
echo("Memcache Message: ". $msg);
break;
default:
echo("Memcache Error: ". $msg);
}
return true;
}

/**
* 构造函数 (初始化分组和连接到服务器)
*/
function MemcacheOpt($hostArray, $hostArray2=array()){
if (!is_array($hostArray) || empty($hostArray)){
$this->showMessage('Memcache host list invalid', 'fatal');
}
$this->groups = array_merge($hostArray, $hostArray2);
$this->splitGroup($hostArray, $hostArray2);
$this->connect();
}
/**
* 对组进行切分 (按照是否需要分组进行相应的切分)
*
* @param array $hostArray 主机数组列表1
* @param array $hostArray2 主机数组列表2
* @return void
*/
function splitGroup($hostArray, $hostArray2=array()){
//如果只有一台机器则不使用分组
if (count($hostArray) < 2 && empty($hostArray2)){$this->isGroup = false;}
//使用分组
if ($this->isGroup){
if (is_array($hostArray2) && !empty($hostArray2)){
$this->group1 = $hostArray;
$this->group2 = $hostArray2;
}else{
$count = ceil(count($hostArray) / 2);
$this->group1 = array_splice($hostArray, 0, $count);
$this->group2 = array_splice($hostArray, 0);
}
}else{$this->group1 = $hostArray;         }
}
/**   * 连接到Memcache服务器   */
function connect(){
if (!is_array($this->group1) || empty($this->group1)){
$this->showMessage("Memcache host1 array invalid", 'error');
return false;
}
//连接第一组Memcache服务器
$this->mmc1 = new Memcache;
foreach($this->group1 as $hosts){
$tmp = explode(":", $hosts);
$host = $tmp;
$port = (!isset($tmp) || $tmp=='') ? $this->mmcPort : $tmp;
$this->mmc1->addServer($host, $port);
}
//如果需要分组则连接第二组Memcache服务器
if ($this->isGroup){
if ( !is_array($this->group2) || empty($this->group2) ){
$this->showMessage("Memcache host2 array invalid", 'error');
return false;
}
$this->mmc2 = new Memcache;
foreach($this->group2 as $hosts){
$tmp = explode(":", $hosts);
$host = $tmp;
$port = (!isset($tmp) || $tmp=='') ? $this->mmcPort : $tmp;
$this->mmc2->addServer($host, $port);
}
}
}
/**   * 关闭Memcache服务器连接   */
function close(){
if (is_object($this->mmc1)){            $this->mmc1->close();      }
if (is_object($this->mmc1)){            $this->mmc1->close();      }      
return true;
}
/**
* 数据操作核心函数
*
* @param string $optType 操作类型,主要有 add, set, replace, delete, flush
* @param string $key 关键字,如果是 add,set,replace,delete 需要提交key参数
* @param string $val 关键字对应的值,如果是 add, set,replace 需要提交value参数
* @param int $expire 数据有效期,如果是 add,set,replace需要提交expire参数
* @return mixed 不同的需要产生不同的返回
*/
function opt($optType, $key='', $val='', $expire=''){
if (!is_object($this->mmc1)){
$this->showMessage("Not availability memcache connection object", 'fatal');
}
if ($this->isGroup && !is_object($this->mmc2)){
$this->showMessage("Group 2 memcache host connection object not availability", 'error');
}
//加入数据操作
if ($optType=='add' || $optType=='set' || $optType=='replace'){
$this->mmc1->set($key, $val, false, $expire);
if ($this->isGroup && is_object($this->mmc2)){
$this->mmc2->set($key, $val, false, $expire);
}
return true;
}
//获取数据操作
if ($optType == 'get'){
//缺省获取第一组数据
if (!$this->isGroup || !is_object($this->mmc2)){
return $this->mmc1->get($key);      
}
//分组情况下逐组访问
$num = ( $this->isRandom ? rand(1, 2) : 1 );
$obj = "mmc". $num;
$val = $this->$obj->get($key);
//如果没有提取到数据,则访问另外一组
if ($val == ""){
switch($num){
case 1: $val = $this->mmc2->get($key); break;
case 2: $val = $this->mmc1->get($key); break;
default: $val = $this->mmc1->get($key);
}
}
return $val;
}
//删除数据操作
if ($optType == 'delete'){
$this->mmc1->delete($key, $expire);
if ($this->isGroup && is_object($this->mmc2)){
$this->mmc2->delete($key);      
}
return true;
}
//清空数据操作   
if($optType == 'flush'){
$this->mmc1->flush();
if ($this->isGroup && is_object($this->mmc2)){
$this->mmc2->flush();      
}
return true;
}
}
//---------------------
//   外部操作方法
//---------------------
//增加一个元素
function add($key, $val, $expire=''){   return $this->opt('add', $key, $val, $expire);   }
//增加一个元素
function set($key, $val, $expire=''){      return $this->opt('set', $key, $val, $expire);    }
//替换一个元素
function replace($key, $val, $expire=''){      return $this->opt('replace', $val, $expire);    }
//获取一个元素
function get($key){      return $this->opt('get', $key);    }
//删除一个元素
function delete($key, $timeout=''){      return $this->opt('delete', $key, '', $timeout);    }
//让所有的元素过期 (本接口不要轻易使用)
function flush(){       return $this->opt('flush');   }

/**   * 获取所有Memcache服务器状态   */
function getStats(){
$status = array();
//单独连接到每台Memcache
foreach($this->groups as $key=>$hosts){
$tmp = explode(":", $hosts);
$host = $tmp;
$port = (!isset($tmp) || $tmp=='') ? $this->mmcPort : $tmp;
$conn = new Memcache;
$conn->connect($host, $port);
$s = $conn->getStats();
$s['host'] = $host;
$s['port'] = $port;
$status[$key] = $s;
}
return $status;
}
/**
* 获取所有Memcache服务器版本号
*/
function getVersion(){
$version = array();
$stats = $this->getStats();
foreach($stats as $key=>$s){
$v['host'] = $s['host'];
$v['port'] = $s['port'];
$v['version'] = $s['version'];
$version[$key] = $v;
}
return $version;
}
}
?>
101:
memcached -d -m 50 -p 11212 -u root
memcached -d -m 50 -p 11213 -u root

102:
memcached -d -m 50 -p 11212 -u root
memcached -d -m 50 -p 11213 -u root
<?php
require_once("MemcacheOpt.class.php");
//操作代码
$hostArray = array("192.168.1.101:11212", "192.168.1.101:11213","192.168.1.102:11212","192.168.1.102:11213");
$m = new MemcacheOpt($hostArray);
$m->add("key1", "key1_value", 30);
$m->add("key2", "key2_value", 30);
$m->add("key3", "key3_value", 30);
$m->add("key4", "key4_value", 30);
echo $m->get("key1"). " ";
echo $m->get("key2"). " ";
echo $m->get("key3"). " ";
echo $m->get("key4"). " ";
print_r($m->getStats());
print_r($m->getVersion());
?>
  今天测试还碰到一个奇怪的问题,下面三段代码都应该是可以执行的,最后一段却报错不能连接,不解。

-----------ok
<?php
$mem = new Memcache;
$mem->connect("127.0.0.1", 11211);
$mem->set('key', 'This is a memcached test!', 0, 60);
$val = $mem->get('key');
echo $val;
?>

--------ok
101:
memcached -d -m 50 -p 11212 -u root
memcached -d -m 50 -p 11213 -u root
<?php
$mem = new Memcache;
$mem->connect("192.168.1.101",11212);
$mem->set('keysss', 'This is a memcached test!', 0, 60);
$val = $mem->get('keysss');
echo $val;
?>
------------------------Warning: Memcache::connect() : Can't connect to 192.168.1.101:11211, Connection refused (111) in /var/www/mem3.php on line 3
memcached启动的时候有一项是指定ip的,如果已经指定了IP.那么可能就无法再使用localhost或127.0.0.1(猜的,不知道是不是这样,俺一般是不指定的,所以默认localhost或127.0.0.1都是可以的)

<?php
$mem = new Memcache;
$mem->connect("192.168.1.101",11211);
$mem->set('keysdf', 'This is a memcached test!', 0, 60);
$val = $mem->get('keysdf');
echo $val;
?>
页: [1]
查看完整版本: 多台memcache 研究