PHP Doku:: Add an item to the server - memcache.add.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige DiensteMemcacheThe Memcache classMemcache::add

Ein Service von Reinhard Neidl - Webprogrammierung.

The Memcache class

<<The Memcache class

Memcache::addServer>>

Memcache::add

(PECL memcache >= 0.2.0)

Memcache::addAdd an item to the server

Beschreibung

bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )

Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Also you can use memcache_add() function.

Parameter-Liste

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben. Returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().

Beispiele

Beispiel #1 Memcache::add() example

<?php

$memcache_obj 
memcache_connect("localhost"11211);

/* procedural API */
memcache_add($memcache_obj'var_key''test variable'false30);

/* OO API */
$memcache_obj->add('var_key''test variable'false30);

?>

Siehe auch


7 BenutzerBeiträge:
- Beiträge aktualisieren...
duerra at nospam dot yahoo dot com
18.11.2010 1:06
If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:

Message: MemcachePool::get(): Failed to uncompress data

The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string. 

<?php
$key
= 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;

$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->add($key, $value, $compress);

echo
$mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->add($key, $value, MEMCACHE_COMPRESSED);
?>
Davide Renzi
18.02.2010 10:16
Race conditions happen on an heavy load server when more than one thread tries to execute memcache_add.
For example if thread A and thread B try to save the same key you can test that sometimes both return TRUE.
To have the right behaviour you can verify that the correct value is in the assigned key:

<?php
function memcache_safeadd(&$memcache_obj, $key, $value, $flag, $expire)
{
    if (
memcache_add($memcache_obj, $key, $value, $flag, $expire))
    {
        return (
$value == memcache_get($memcache_obj, $key));
    }
    return
FALSE;
}
?>
matt
4.08.2009 3:39
It's also good to note that add will succeed if the key exists but is expired
ktamas77 at gmail dot com
27.04.2009 13:08
skeleton of a thread safe updater for an incremental counter:

<?php

$key
= "counter";
$value = $memcache->increment($key, 1);
if (
$value === false) {
  
// --- read from DB ---
  
$query = "SELECT value FROM database";
  
$result = mysql_query($query);
  
$row = mysql_fetch_assoc($result);
  
$db_value = $row["value"];
  
$add_value = $memcache->add($key, $db_value + 1, 0, 0);
   if (
$add_value === false) {
     
$value = $memcache->increment($key, 1)
      if (
$value === false) {
         
error_log ("counter update failed.");
      }
   } else {
     
$value = $db_value + 1;
   }
}

// --- display counter value ---
echo $value;

?>
rune(at)intermedia(dot)no
6.10.2008 20:04
Key may not exceed 250 chars according to memcached protocol.
php at tapirpirates dot net
3.04.2008 18:32
memcache has no locking mechanism, but you could implement it manually.

basic locking through the add method:

<?php
// locks time out after 5 seconds
Define( 'LOCK_TIMEOUT', 5 );

$lock = $memcache->add( 'lock:' . $key, 1, false, LOCK_TIMEOUT );
if (
$lock ) {
 
// no lock on this key, so do what you want
 
$value = $memcache->get( $key );
 
$memcache->set( $key, $value+1 );
 
// release lock
 
$memcache->delete( 'lock:' . $key );
}
else {
 
// variable is currently locked, so do something else
}
?>

furthermore, you could implement a loop which checks if there is a lock, and if there is, wait some time and try again, until the lock is free.

remember: locking will heavily increase your memcache hits and obviously is not what memcache is made for. altough it's not possible for a lock to be forgotten (there's a timeout after all) there is the possibility to get locked out for a very long time.

an alternative may be to implement locking through apc_add (or shared memory), but i've never tried it.

if you absolutley have to implement locks, memcached is probably the wrong solution anyway.
roberto at spadim,com dot br
18.06.2007 7:13
[c.2007]
if you read source code for MMC_SERIALIZED you will see at line ~1555 that [a line ~1560]
!(is_string,is_long,is_double,is_bool)

[is] serialized and that serialized values are flaged as MMC_SERIALIZED for return (fetch) code unserialize these values again



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)