我正在尝试从php脚本中保存memcached中的数据,以便我的网站可以直接使用这些数据

时间:2013-11-12 06:18:29

标签: php codeigniter memcached

脚本工作正常并且正在设置数据,但网站代码无法使用它,而是设置自己的memcached值。我的网站代码是用codeIgniter框架编写的。我不知道为什么会这样。

我的脚本代码: -

function getFromMemcached($string) {

    $memcached_library = new Memcached();
    $memcached_library->addServer('localhost', 11211);
    $result = $memcached_library->get(md5($string));
    return $result;
}

 function setInMemcached($string,$result,$TTL = 1800) {
    $memcached_library = new Memcached();
    $memcached_library->addServer('localhost', 11211);
    $memcached_library->set(md5($string),$result, $TTL);
}

/*---------- Function stores complete product page as one function call cache -----------------*/
 function getCachedCompleteProduct($productId,$brand)
{
    $result = array();
    $result = getFromMemcached($productId." product page");


    if(true==empty($result))
    {
       //------- REST CODE storing data in $result------

            setInMemcached($productId." product page",$result,1800);    
    }
   return $result;      
}

网站代码: -

private function getFromMemcached($string) {
    $result = $this->memcached_library->get(md5($string));
    return $result;
}

private function setInMemcached($string,$result,$TTL = 1800) {
    $this->memcached_library->add(md5($string),$result, $TTL);
}

/*---------- Function stores complete product page as one function call cache -----------------*/
public function getCachedCompleteProduct($productId,$brand)
{
    $result = array();
    $result = $this->getFromMemcached($productId." product page");


    if(true==empty($result))
    {
    // ----------- Rest Code storing data in $result

    $this->setInMemcached($productId." product page",$result,1800);     
    }
   return $result;      
}

这是在memcached中保存数据。我通过在if条件内打印检查并检查最终结果

1 个答案:

答案 0 :(得分:1)

根据CodeIgniter文档,您可以使用:

class YourController extends CI_Controller() {
  function __construct() {
    $this->load->driver('cache');
  }

  private function getFromMemcached($key) {

    $result = $this->cache->memcached->get(md5($key));
    return $result;
  }

  private function setInMemcached($key, $value, $TTL = 1800) {
    $this->cache->memcached->save(md5($key), $value, $TTL);
  }

  public function getCachedCompleteProduct($productId,$brand) {
    $result = array();
    $result = $this->getFromMemcached($productId." product page");

    if( empty($result) ) {
      // ----------- Rest Code storing data in $result
      $this->setInMemcached($productId." product page",$result,1800);  
    }
    return $result;      
  }
}

如果第三方库已经存在于核心框架中,请亲自尝试避免使用它。我已经对此进行了测试,它运行得非常好,所以应该为你解决这个问题:)

请记住按照http://ellislab.com/codeigniter/user-guide/libraries/caching.html#memcached中的说明设置memcache服务器所需的配置