Memcache::add

memcache_add

(PECL memcache >= 0.2.0)

Memcache::add -- memcache_addAdiciona um item ao servidor

Descrição

Memcache::add(
    string $key,
    mixed $var,
    int $flag = ?,
    int $expire = ?
): bool
memcache_add(
    Memcache $memcache,
    string $key,
    mixed $var,
    int $flag = ?,
    int $expire = ?
): bool

Memcache::add() armazena a variável var com a chave key somente se tal chave ainda não existir no servidor.

Parâmetros

key

A chave que será associada ao item.

var

A variável a ser armazenada. Strings e inteiros são armazenados como estão, outros tipos são armazenados serializados.

flag

Use MEMCACHE_COMPRESSED para armazenar o item compactado (usa zlib).

expire

Tempo de expiração do item. Se for igual a zero, o item nunca irá expirar. Pode-se também usar o timestamp Unix ou um número de segundos começando no horário atual, mas no último caso o número de segundos não pode exceder 2592000 (30 dias).

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha. Retorna false se tal chave já existir. Para o resto Memcache::add() se comporta similarmente a Memcache::set().

Exemplos

Exemplo #1 Exemplo de Memcache::add()

<?php

$memcache_obj
= memcache_connect("localhost", 11211);

/* API procedural */
memcache_add($memcache_obj, 'chave_var', 'variável de teste', false, 30);

/* API orientada a objeto */
$memcache_obj->add('chave_var', 'variável de teste', false, 30);

?>

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês) 5 notes

up
8
vasiliy at hotger dot com
11 years ago
It looks like add() function is truly 100% atomic, and safeadd bicycle mentioned in the other comment is useless. There are few links where developers of Memcahed explained it deeper

http://lists.danga.com/pipermail/memcached/2008-March/006647.html
http://www.serverphorums.com/read.php?9,214222
up
4
Davide Renzi
15 years ago
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;
}
?>
up
3
ktamas77 at gmail dot com
15 years ago
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;

?>
up
0
matt
15 years ago
It's also good to note that add will succeed if the key exists but is expired
up
-2
roberto at spadim,com dot br
17 years ago
[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
To Top