function getData$sql global $db $pool; 生成缓存key $cacheKey = md5$sql; 读取缓存如果有 $result = $pool-get$cacheKey; if $result === false 如果缓存中没有数据则从数据库中读取 $queryResult = mys
function getData($sql, $cacheTime = 3600) { global $db, $pool; // 生成缓存key $cacheKey = md5($sql); // 读取缓存(如果有) $result = $pool->get($cacheKey); if ($result === false) { // 如果缓存中没有数据,则从数据库中读取 $queryResult = mysqli_query($db, $sql); if (!$queryResult) { throw new Exception('SQL Error: ' . mysqli_error($db)); }
$data = array();
while ($row = mysqli_fetch_array($queryResult, MYSQLI_ASSOC)) {
$data[] = $row;
}
// 将从数据库中读取的数据存入缓存
if (!$pool->set($cacheKey, $data, $cacheTime)) {
throw new Exception('Failed to store data in cache');
}
// 返回数据
return $data;
} else {
// 如果缓存中有数据,则直接使用缓存中的数据
// 返回数据
return $result;
}
}
原文地址: https://www.cveoy.top/t/topic/bep8 著作权归作者所有。请勿转载和采集!