首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PDO Memcached PHP

PDO Memcached PHP
EN

Stack Overflow用户
提问于 2014-03-15 23:33:01
回答 1查看 2.3K关注 0票数 1

我正试图将memcached实现到我的服务器上,因为数据库的大小变得如此之快。我想知道如何将其实现到以下代码中:

代码语言:javascript
复制
    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>';
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-16 00:06:29

这就是你要的

代码语言:javascript
复制
  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)值==>从数据库中获取的对象、结果集

//伪码

代码语言:javascript
复制
if ( Get data from memcache passed )
  {
    return result;
  }
  else
  {
    get the data from database
    save it into memcache
   }

注意:如果您在单个服务器上运行,最好是查看APC,而不是memcached。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22431090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档