你能在Memcache中存储一个数组吗?
我想要存储:
- 用户ID号码
- 用户的照片URL
- 用户的名字
作为一个数组一起存储,有人告诉我可以,但也有人告诉我不行,究竟是哪个呢?
Memcache::set('someKey', array(
'user_id' => 1,
'url' => 'http://',
'name' => 'Dave'
));
在Memcache中,一项的最大存储大小为1,048,576字节(1MB),将数组序列化会占用一定的空间。
如果您将数组结构简单化,例如:
array(
[0] => 1,
[1] => 2,
[2] => 3
)
键自动生成,值为用户ID。
使用此结构对5000个编号为1-5000的用户进行序列化数组,字符串长度为67792个字符,50000个用户产生777794个字符的数组。
对100000到150000进行编号,产生一个序列化字符串,长度为838917个字符。
因此,在50k个用户(如您先前提到的)时,您很可能不会超过1MB的限制。但是,如果您有本地缓存(例如APC等),请使用它,或者如果出于任何原因您不需要一次获取所有ID,则强烈建议拆分结果或仅使用数据库。
还要考虑您在memcached中存储的数据结构。如果您只是使用缓存来提供要查找的主键列表,那么是否需要其他数据?
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");
$id = $_REQUEST['name'];
$key = md5("SELECT * FROM memc where FirstName='{$id}'");
$get_result = array();
$get_result = $memcache->get($key);
if ($get_result) {
echo "<pre>\n";
echo "FirstName: " . $get_result['FirstName'] . "\n";
echo "Age: " . $get_result['Age'] . "\n";
echo "</pre>\n";
} else {
$query="SELECT * FROM memc where FirstName='{$id}'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo "<pre>\n";
echo "FirstName: " . $row[1] . "\n";
echo "Age: " . $row[3] . "\n";
echo "Retrieved from the Database\n";
echo "</pre>\n";
$memcache->set($key, $row, MEMCACHE_COMPRESSED, 60);
mysql_free_result($result);
}
你可以将几乎任何想要存储的内容存储在memcached中。
请参阅memcache::set
的文档,其中写道:
bool Memcache::set(string $key, mixed $var [, int $flag [, int $expire ]] )
var
The variable to store. Strings and integers are stored as is, other types
are stored serialized.
所以,是的,如果需要,你可以存储一个数组,甚至是一个对象 :-)
顺便说一下,Memcache::add
和 Memcache::replace
的情况也是一样的