SunshinePHP Developer Conference 2015

Memcached::cas

(PECL memcached >= 0.1.0)

Memcached::casCompare and swap an item

Beschreibung

public bool Memcached::cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )

Memcached::cas() performs a "check and set" operation, so that the item will be stored only if no other client has updated it since it was last fetched by this client. The check is done via the cas_token parameter which is a unique 64-bit value assigned to the existing item by memcache. See the documentation for Memcached::get*() methods for how to obtain this token. Note that the token is represented as a double due to the limitations of PHP's integer space.

Parameter-Liste

cas_token

Unique value associated with the existing item. Generated by memcache.

key

Der Schlüssel, unter dem der Wert abgelegt werden soll.

value

Der zu speichernde Wert.

expiration

Die Verfallszeit, Vorgabewert ist 0. Siehe Verfallszeiten für weiterführende Informationen.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

Beispiele

Beispiel #1 Memcached::cas() example

<?php
$m 
= new Memcached();
$m->addServer('localhost'11211);

do {
    
/* fetch IP list and its token */
    
$ips $m->get('ip_block'null$cas);
    
/* if list doesn't exist yet, create it and do
       an atomic add which will fail if someone else already added it */
    
if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        
$ips = array($_SERVER['REMOTE_ADDR']);
        
$m->add('ip_block'$ips);
    
/* otherwise, add IP to the list and store via compare-and-swap
       with the token, which will fail if someone else updated the list */
    
} else { 
        
$ips[] = $_SERVER['REMOTE_ADDR'];
        
$m->cas($cas'ip_block'$ips);
    }   
} while (
$m->getResultCode() != Memcached::RES_SUCCESS);

?>

Siehe auch

add a note add a note

User Contributed Notes 1 note

up
0
abodera at gmail dot com
4 years ago
Watch out!

When using binary protocol, the expected result after cas() is 21 (Memcached::RES_END).

For example, to make the above example #1 work with binary protocol, use the following:
<?php
$m
= new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_BINARY_PROTOCOL,true)

// [...]

   
} else {
       
$ips[] = $_SERVER['REMOTE_ADDR'];
       
$m->cas($cas, 'ip_block', $ips);
    }  
} while (
$m->getResultCode() != Memcached::RES_END);
?>
To Top