php memcached缓存集群

一、需求描述

一linode xen vps 1G RAM,40+sites,IO频繁,openfilesulimit已65535

US时间访问量大增,nginx不定时502

二、解决办法

pages cache化,但这一台vps内存不够用,于是把闲置的几台服务器都装上memcached做缓存集群

再根据网络延迟设定权重

memcached server官方: http://memcached.org/

三、代码

访问memcached server需要php支持,可以选择memcached库和memcache库,注意2者名字的区别

详细对比:https://code.google.com/p/memcached/wiki/PHPClientComparison

我采用的是php memcache:http://php.net/manual/en/book.memcache.php因为memcache不依赖libmemcached

1
2
3
4
5
6
7
8
9
10
11
//集群数组
$memserver = array (
array ( 'host' => 'fast1.xxx.com' , 'port' => 13579 , 'weight' => 40 ),
array ( 'host' => 'fast2.xxx.com' , 'port' => 13579 , 'weight' => 20 ),
array ( 'host' => 'fast3.xxx.com' , 'port' => 13579 , 'weight' => 20 ),
array ( 'host' => 'slow1.xxx.com' , 'port' => 24680 , 'weight' => 5 ),
array ( 'host' => 'slow2.xxx.com' , 'port' => 24680 , 'weight' => 5 ),
array ( 'host' => 'local.xxx.com' , 'port' => 11211 , 'weight' => 10 )
);

键值读、写、删就没什么说的了直接按文档sample写即可
考虑到以后的移植问题,记得首先检测环境是否支持memcache: class_exists(‘Memcache’)
下面是我的实现,因为特定需求,几个函数写的相对独立,memcache也没做全局实例化。
你可以根据自己需求把memcache在全局实例化,优化操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//---get content from memcache---
function getCache( $key )
{
Global $memserver ;
$ret = false;
$key = md5( $key );
$mc = new Memcache();
foreach ( $memserver as $s )
$mc ->addServer( $s [ 'host' ], $s [ 'port' ], FALSE, $s [ 'weight' ] );
$ret = $mc ->get( $key );
$mc ->close();
unset( $mc );
return $ret ;
}
//---set content from memcache---
function setCache( $key , $val )
{
Global $memserver ;
$ret = false;
$key = md5( $key );
$mc = new Memcache();
foreach ( $memserver as $s )
$mc ->addServer( $s [ 'host' ], $s [ 'port' ], FALSE, $s [ 'weight' ] );
if ( isset( $val [ 'cached' ]) )
{
$val [ 'cached' ] = 1;
$ret = $mc ->set( $key , $val );
}
$mc ->close();
unset( $mc );
return $ret ;
}
//---delete content from memcache---
function delCache( $key )
{
Global $memserver ;
$ret = false;
$key = md5( $key );
$mc = new Memcache();
foreach ( $memserver as $s )
$mc ->addServer( $s [ 'host' ], $s [ 'port' ], FALSE, $s [ 'weight' ] );
$ret = $mc -> delete ( $key , 0);
$mc ->close();
unset( $mc );
return $ret ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值