php memcached缓存集群
一、需求描述一linode xen vps 1G RAM,40+sites,IO频繁,openfiles ulimit已65535US时间访问量大增,nginx不定时502二、解决办法pages cache化,但这一台vps内存不够用,于是把闲置的几台服务器都装上memcached做缓存集群再根据网络延迟设定权重memcached server官方:
一、需求描述
一linode xen vps 1G RAM,40+sites,IO频繁,openfiles ulimit已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)