我想知道如何使用缓存 (MemCache) 来显示我的网站上有多少注册用户和活跃用户。我目前使用:
return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0);
这不好用,因为在每次加载页面时,它都会查询数据库。这不好。那么我将如何继续制作“内存缓存”或类似的东西,它会在大约 10 分钟后向所有用户更新该数字?
我用谷歌搜索了如何操作,但我无法真正找到一个好的操作方法。
谢谢!
最佳答案
我会给你指南而不是完整的文档/教程。
在尝试安装 Memcached 之前,您应该使用 MySQLi或 PDO而不是 mysql_* 函数。查看 this documentation 中的警告消息.
你应该install Memcached及其 PHP extension .
完成后,通过调用函数 phpinfo() 确保它已启用.如果没有 Memcached,则安装失败。
这是一个明确的代码片段
$mc = new Memcached();
$mc->addServer('localhost', 11211); // add a new server to the pool
// you will want to vary this key according to the query
// if two different queries use the same key your functions will return unexpected data
$cacheKey = 'a-custom-key-that-defines-the-data-within-it';
// how long will it take for the cache to expire in seconds : an hour
$cacheLifetime = 3600;
$data = $mc->get($cacheKey); // we get the data from cache
// check if Memcached was able to retrieve the data
if ($mc->getResultCode() === Memcached::RES_FAILURE) {
// if for some reasons the data is not there we get it and reinject into memcached
$data = mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0);
$mc->set($cacheKey, $data, $cacheLifetime); // save the data in the defined $cacheKey
}
return $data;
关于php - 如何使用 Memcached 存储给定时间的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444715/