简体   繁体   中英

Why is memcache php extension (or memcached) so unreliable?

I am disappointed with memcached. Working with it has been far from easy.

An example:

$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");

$memcache->set('id', $array, 120);

I set this about an hour ago - and it is still there! The manual says can use the "number of seconds starting from current time" as parameter. So why is the expiry ignored?

Another thing that bugs me is that sometimes values are not written. It all is pretty much random. "argyleblanket" mentioned running into those problems in the php manual: http://www.php.net/manual/en/memcache.set.php#84032 I have implemented that fallback on all my replace() calls as well. I don't get why it won't just work on the first call. Why offer a replace() function if it's in the stars if it replaces the content or not?

The question is why would I trust such a software to do anything of importance and is there a way to make it more reliable?

You're using wrong syntax. The 3rd parameter is the compression flag.

Make a simple interface such as this following. It can help you:

/* defines params */
define('MEMCACHED',     1);
define('CACHE_DEFAULT_EXPIRE',  3600);

if(MEMCACHED) if(! class_exists('memcached')) die('memcache not loaded');

/* Cache */
if(MEMCACHED) { 
    global $memcache;
    $memcache = new Memcache();
    $memcache->connect('127.0.0.1', 11211);
}

function cacheSet($key, $var, $expire=NULL) {
    if(!MEMCACHED) return 0;
    global $memcache;
    if(!$expire) $expire = CACHE_DEFAULT_EXPIRE;
    $key = md5($key);
    return $memcache->set($key, $var, false, $expire);
}

function cacheGet($key) {
    if(!MEMCACHED) return 0;
    global $memcache;
    $key = md5($key);
    return $memcache->get($key);
}

The third parameter is Memcache::set is $flag , not $expire . $expire is the fourth one:

$memcache = new Memcache;
// add server, etc.
$memcache->set('foo', 'bar', 0, 5); // 5 seconds expiry
var_dump($memcache->get('foo')); // bar
sleep(6);
var_dump($memcache->get('foo')); // false

The syntax you are using is for the Memcached class, not Memcache .

As for your problem with set/replace, I can't reproduce this with either Memcache or Memcached on PHP 5.3.3.

Also, in my opinion, you should go for the PECL memcached extension. It provides more features and uses libmemcached directly, so it also should be more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM