PDO Memcached PHP

gu

由于数据库是如此之快,我正在尝试将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>';
    }
}
我要学习

干得好

  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>';
    }
}

在网站中使用内存缓存时的逻辑。是md5的sql查询,所以它们将是唯一的。首先,您尝试从memcached中获取(使用md5作为sql查询),因此它将成为关键。如果什么都没得到,则从数据库中获取数据,然后将其保存到内存缓存中。这意味着您对sql查询进行md5设置,使其成为键,这样它将是唯一的,并且将数据库返回的结果作为其值传递

键===> md5(Sql Query)值==>从数据库中获取的对象,结果集

//伪代码

if ( Get data from memcache passed )
  {
    return result;
  }
  else
  {
    get the data from database
    save it into memcache
   }

注意:如果您在单台服务器上运行,最好查看APC,而不要使用memcached

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章