php - 使用 predis 在 redis 中存储 mysql 查询

标签 php mysql redis predis

我想使用redis缓存将mysql查询存储在redis中,第一次按预期工作(因为redis中没有key)并执行查询,但后来$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;

最佳答案

您需要遍历查询结果,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;

关于php - 使用 predis 在 redis 中存储 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34577755/

相关文章:

php - Centos无法安装mysqli

php - 谷歌 API OAuth 2.0 CURL 返回 "Required parameter is missing: grant_type"

mysql - 原因 : liquibase. 异常。MySQL 5.7 中带有 DELETE 语句的DatabaseException

php - 无法通过 CodeIgniter 连接到远程数据库

mysql 无法与 xampp 一起使用

php - 从 mysql 行 pdo 获取值

php - 自动更新没有模型的表中的时间戳

redis - 使用 Redis SORTED SET 让用户 friend 获得最高评价的最佳方式

amazon-web-services - 如何将 elasticache redis 集群设置为从属?

amazon-web-services - 无法将 Redis 集群扩展到超过 90 个节点