Memcache不设置密钥

时间:2012-04-28 15:25:02

标签: php memcached set

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

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

用于缓存的db类:

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);
        }
    }

可悲的是,即使所有资源都能正常运行,也不会将任何数据设置为缓存。 AKA我的页面输出:

  • 这不是缓存查询:SELECT * FROM lang WHERE pg ='front' LIMIT 2
  • Md4:34aa4e46a15413f5091dac79c9e86306
  • 类型的资源(7)(mysql结果)

有人会非常友好地告诉我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

错字:

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

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

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

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

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