php - 如何使用 Memcached 存储给定时间的数据

标签 php mysql memory memcached

我想知道如何使用缓存 (MemCache) 来显示我的网站上有多少注册用户和活跃用户。我目前使用:

    return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` =    1"), 0);

这不好用,因为在每次加载页面时,它都会查询数据库。这不好。那么我将如何继续制作“内存缓存”或类似的东西,它会在大约 10 分钟后向所有用户更新该数字?

我用谷歌搜索了如何操作,但我无法真正找到一个好的操作方法。

谢谢!

最佳答案

我会给你指南而不是完整的文档/教程。

在尝试安装 Memcached 之前,您应该使用 MySQLiPDO而不是 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/

相关文章:

php - 如何在 PHP 中使用 str_replace() 替换 "\"?

php - 在 php 中创建嵌套的 JSON 对象?

sql - "IN"查询中值的数量限制

mysql - 无法从 Windows Azure VM 连接 Linux Azure VM

c# windows 应用程序 - 分析峰值内存使用情况并确定趋势

php - 使用 PHP 从网页中提取特定数据

javascript - 调用后处理来自ajax请求的数据

php - 调用数组 laravel 上的成员函数 where()

java - 分析 JNI 应用程序

python - 在python中访问内存地址