0

该脚本工作正常并正在设置数据,但网站代码无法使用它,而是设置自己的 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 条件内打印并检查最终结果来检查

4

1 回答 1

1

Based on the CodeIgniter docs, you can make use of:

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

Personally try to avoid 3rd party libraries if it already exists in the core framework. And I have tested this, it's working superbly, so that should fix this for you :)

Just remember to follow the instructions at http://ellislab.com/codeigniter/user-guide/libraries/caching.html#memcached to set the config as needed for the memcache server

于 2013-11-15T23:19:32.883 回答