使用predis在redis中存储mysql查询

时间:2016-01-03 14:42:02

标签: php mysql redis predis

我想使用redis缓存在redis中存储mysql查询,第一次按预期工作(因为redis中没有键)并执行查询,但稍后$rs = @unserialize( $redis->get($key)不返回任何内容;我尝试了很多解决方案,但没有运气,我的代码如下:

require __DIR__ . '/vendor/autoload.php';
Predis\Autoloader::register();

$redis = new Predis\Client(array(
    "scheme" => "tcp",           
    "host" => "127.0.0.1",       
    "port" => 6379,              
    "password" => "testRedis")); 

$sql="SELECT * FROM news where status=1 and (title like \"%$sword%\" or body like \"%$sword%\" or name like \"%$sword%\" or rss like \"%$sword%\")";

$key = "sql_cache:" . md5($sql);

if ($rs = @unserialize( $redis->get($key) ) === false){ 

    $rs = mysql_query($sql)or die(mysql_error());       

    // Put data into cache for 1 hour                   
    $redis->set($key, serialize($rs));                  
    $redis->expire($key, 3600);                           
}                                                       
echo 'rs= '.$rs;                                   
$nr = @mysql_num_rows($rs);                             
echo "Number of rows: " . $nr;

1 个答案:

答案 0 :(得分:2)

您需要遍历查询结果,mysql_query返回的资源无法序列化。

您可以尝试以下方式:

$key = "sql_cache:" . md5($sql);
// If $key exists get and unserialize it, otherwise set $data to empty array
$data = $redis->exists($key) 
    ? unserialize($redis->get($key)) 
    : array();

if (empty($data)) { 
    $rs = mysql_query($sql);       
    if ($rs === false) {
        die(mysql_error());
    }
    // Iterate through results...
    while ($row = mysql_fetch_assoc($rs)) {
        $data[] = $row;
    }

    // Put data into cache for 1 hour                   
    $redis->set($key, serialize($data));                  
    $redis->expire($key, 3600);                           
}                                                       
echo 'data= '.$data;                                   
$nr = count($data);                             
echo "Number of rows: " . $nr;