gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:13:21 24 4
gpt4 key购买 nike

我想使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com