php - 在类中使用 memcache

标签 php mysql memcached

所以我昨天才开始学习如何使用memcache。所以还有很多事情要做。到目前为止,我已经了解了如何安装它,并看到了一些有关如何使用它的教程。但他们都解释了如何静态地输入它。我在类中执行所有数据库查询,并运行 foreach 循环返回的数据。我让它工作,没有任何编译错误,但内存缓存实际上无法工作。我很困惑为什么。我的类(class)就是这样设置的。

class Feed extends Database
{
private $Memcache;

public function __construct()
{
    parent::__construct();
    $this->Memcache = new Memcache;
} //end __construct

public function getFeed ($var)
{
    $feed = array(); //Initialize an empty array

    $this->Memcache->connect('localhost', 11211);
    $key = "SELECT col FROM table WHERE value = " . $var . " ORDER BY timestamp DESC LIMIT 30";
    $cache = $this->Memcache->get($key);
    if ($cache)
    {
        $feed = '';
    }
    else
    {
        //Query the database
        $Statement = $this->Database->prepare("SELECT col FROM table WHERE value = ? ORDER BY timestamp DESC LIMIT 30");
        $Statement->execute(array($var));


        while($row = $Statement->fetch(PDO::FETCH_ASSOC))
        {
            $feed[] = array("row1" => $row["col1"], 
                            "row2" => $row["col2"] );

        }

        $this->Memcache->set($key, $row, 0, 40); // Store the result of the query for 40 seconds
    }

    return $feed;
} //end getFeed
} //end Feed

输出设置如下

<?php foreach ($Feed->getFeed($var) as $feed): ?>

    <p><?php echo $feed["row1"]; ?></p>

<?php endforeach; ?>

很明显,如果内存缓存正在工作,它们将是一个编译错误,因为我使用 foreach 循环运行 $feed 。由于我对内存缓存的了解有限,你们知道为什么它不检索数据吗?

非常感谢您!

最佳答案

来自内存缓存 protocol description :

Keys

Data stored by memcached is identified with the help of a key. A key is a text string which should uniquely identify the data for clients that are interested in storing and retrieving it. Currently the length limit of a key is set at 250 characters (of course, normally clients wouldn't need to use such long keys); the key must not include control characters or whitespace.

您的 key 包含空格字符,因此失败。您可以检查这一点,因为 Memcache::set() 在失败时返回 FALSE。

防止这种情况的简单方法:从您的 $key 创建 MD5 哈希并将其用作 $key:

$key = md5("SELECT col FROM table WHERE value = " . $var . " ORDER BY timestamp DESC LIMIT 30");

注意:Memcache 值不能大于 1MB。

关于php - 在类中使用 memcache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15347704/

相关文章:

php - 转换为 Codeigniter 查询

php - Symfony2 - Twig - 如何将参数发送到父模板?

java - Spring MVC - 在内存中创建一个 ZIP 文件并让用户下载

python - 解释如何在Python中使用内存缓存

php - 网页游戏的数据库建模

PHP readfile 或 file_get_contents 在循环中

python - Django 表单 - 使用数据库中的变量

mysql - 关于如何设计一个存储多种类型帖子数据的数据库(mysql)有什么建议吗?

ruby-on-rails - Rails 使用 memcached 进行缓存,无法正常工作

java - 应用缓存对比hibernate二级缓存,用哪个?