Memcache 不设置密钥


Memcache doesn't set keys

我遇到了Memcache无法设置密钥的问题。基本上我有我的测试页面:

$db=new db;
$my_test_cache=$db->query("SELECT `txt` FROM `lang` WHERE `pg`='front' LIMIT 2", 10);

还有一个用于缓存的数据库类:

class db {
        public function query($query, $ttl=30, $cache=true, $compr=false) {
            global $memcache;
            if ($cache==true) {
                $res=$memcache->get(hash('md4', $query));
                if ($res!=false) {
                    echo 'this is cached';
                    return $res;
                }
                else {
                    $res=mysql_query($query);
                    $memcache->set(hash('md4', $query), $res, $compr, $ttl);
                    echo 'this is not cached<hr>
                    Query: ',$query,'<br/>
                    Md4: ',hash('md4',$query),'<br/>';
                    var_dump($res);
                    return $res;
                }
            }
            else return mysql_query($query);
            unset($res, $query);
        }
    }

可悲的是,这不会将任何数据设置为缓存,即使所有资源似乎都正常工作。又名我的页面输出:

  • 这不是缓存 查询:从lang中选择 * 其中 pg ='正面'限制 2
  • Md4: 34aa4e46a15413f5091dac79c9e86306
  • 资源(7) 类型(MySQL 结果)

有人会好心地告诉我在这里做什么吗?

拼写错误:

        if ($cache=true) {
                  ^--- should be ==

同样,除非 memcache 比我想象的要聪明得多,否则你只是缓存一个查询结果句柄,而不是实际的查询结果:

       $memcache->set(hash('md4', $query), $res, $compr, $ttl);
                                           ^^^^

此时,$res只是一个随机数字,而不是您请求的txt字段。您必须首先从该结果中获取一行才能检索数据:

       $result = mysql_query(...) or die(mysql_error());
       $row = mysql_fetch_assoc($result);
       $txt = $row['txt'];