【发布时间】:2010-11-15 06:18:46
【问题描述】:
你能在 Memcache 中存储一个数组吗?
我想存储;
- 用户 ID 号
- 用户的照片网址
- 用户名
作为一个数组,有人告诉我你可以,然后有人告诉我你不能 是哪个?
【问题讨论】:
你能在 Memcache 中存储一个数组吗?
我想存储;
作为一个数组,有人告诉我你可以,然后有人告诉我你不能 是哪个?
【问题讨论】:
$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);
}
根据您的要求添加更改数据库设置,测试代码请尝试
【讨论】:
memcache 中项目的最大存储大小为 1,048,576 字节 (1MB),序列化数组确实需要一些空间。
如果你要像这样简单地构造你的数组:
array(
[0] => 1,
[1] => 2,
[2] => 3
)
key 是自动生成的,value 是用户 ID。
使用此结构编号为 1-5000 的 5000 个用户的序列化数组的字符串长度为 67792 个字符,50000 个用户生成一个包含 777794 个字符的数组。
编号 100000 到 150000 会生成一个包含 838917 个字符的序列化字符串。
因此,如果用户数为 50k(如您之前的问题中所述),您可能会低于 1MB 的限制。如果您有本地缓存(APC 等),请改用它,或者如果出于任何原因不需要一次所有的 ID,我强烈建议拆分结果或仅使用 DB。
还要考虑您存储在 memcached 中的数据结构。如果您使用缓存只是为了给您提供要查找的主键列表,您还需要其他数据吗?
【讨论】:
是的。
Memcache::set('someKey', array(
'user_id' => 1,
'url' => 'http://',
'name' => 'Dave'
));
有关非常详细的示例,请参阅documentation。
【讨论】:
你几乎可以在 memcached 中存储任何你想要的东西。
请参阅memcache::set 的文档,其中说:
bool Memcache::set(string $key, mixed $var [, int $flag [, int $expire ]] )
变量
The variable to store. Strings and integers are stored as is, other types被序列化存储。
所以,是的,如果需要,您可以存储一个数组,甚至是一个对象 :-)
顺便说一句,Memcache::add 和 Memcache::replace 是一样的
【讨论】: