我正试图将memcached实现到我的服务器上,因为数据库的大小变得如此之快。我想知道如何将其实现到以下代码中:
function getWorkers($db)
{
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);
$del = $db->prepare('SELECT DISTINCT(address) from works');
$del->execute();
$arr = $del->fetchAll();
$works = getMaxWork($db);
foreach($arr as $a)
{
$del = $db->prepare('SELECT * FROM works WHERE address = \'' . $a[0] . '\'');
$del->execute();
$work = $del->rowCount();
echo '<tr>';
echo '<td>' . htmlspecialchars($a[0], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td>' . $work . '</td>';
echo '<td>' . round(intval($work)/intval($works)*100, 2) . '</td>';
echo '</tr>';
}
}发布于 2014-03-16 00:06:29
这就是你要的
function getData($db)
{
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);
$sqlQuery = 'SELECT DISTINCT(address) from works';
$memcacheKey = md5($sqlQuery);
if ( $arr = $meminstance->get(memcacheKey) )
{
// its in cache do nothing
}
else
{
// its not in cache, so we came here, lets now get it from db and cache it
$del = $db->prepare($sqlQuery);
$del->execute();
$arr = $del->fetchAll();
$works = getMaxWork($db);
// lets now cache it
$meminstance->set(memcacheKey,$arr);
}
foreach($arr as $a)
{
$sqlQuery = 'SELECT * FROM works WHERE address = \'' . $a[0] . '\'';
$memcacheKey = md5($sqlQuery);
if ( $del = $meminstance->get($memcacheKey))
{
//its in cache yaaaaaaaa :D
}
else
{
$del = $db->prepare('SELECT * FROM works WHERE address = \'' . $a[0] . '\'');
$del->execute();
$work = $del->rowCount();
// lets cache it here
$meminstance->set($memcacheKey,$del);
}
echo '<tr>';
echo '<td>' . htmlspecialchars($a[0], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<td>' . $work . '</td>';
echo '<td>' . round(intval($work)/intval($works)*100, 2) . '</td>';
echo '</tr>';
}
}当您在网站中使用memcache时的逻辑。它是md5的查询,所以它们将是唯一的。您首先尝试从memcached获取,( md5查询),所以它将是关键。如果您没有得到任何信息,您可以从数据库中获取数据,然后将其保存到memcache中。这意味着您要将sql查询设置为md5键,以便它是唯一的,并将从数据库返回的结果作为其值传递。
键===> md5(Sql Md5)值==>从数据库中获取的对象、结果集
//伪码
if ( Get data from memcache passed )
{
return result;
}
else
{
get the data from database
save it into memcache
}注意:如果您在单个服务器上运行,最好是查看APC,而不是memcached。
https://stackoverflow.com/questions/22431090
复制相似问题