簡體   English   中英

PDO Memcached PHP

[英]PDO Memcached PHP

由於數據庫是如此之快,我試圖將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中獲取(您對md sql進行md5查詢),因此它將成為關鍵。 如果什么都沒得到,則從數據庫中獲取數據,然后將其保存到內存緩存中。 這意味着您對sql查詢進行md5設置,使其成為關鍵字,這樣它將是唯一的,並且您將從數據庫返回的結果作為其值傳遞

鍵===> md5(Sql Query)值==>從數據庫獲取的對象,結果集

//偽代碼

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

注意:如果您在單台服務器上運行,最好查看APC而不是內存緩存

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM