a word of caution - i was working on a PHP install where (apparently) ZLIB compression was not enabled, but using the MEMCACHE_COMPRESSED flag.
instead of throwing an error or warning when i tried to set cache, it just failed silently...it took a little while to track down why my database was still getting hit when the stuff 'should' have been in memcached...
so...make sure zlib is available, or don't use this flag.
jsh
jinglesboiler AT gmail
Memcache::set
(PECL memcache >= 0.2.0)
Memcache::set — Stocke des données dans le serveur de cache
Description
Memcache::set() stocke l'élément var avec la clé key sur le serveur de cache. Le paramètre expire représente le délai en secondes d'expiration de l'élément. S'il vaut 0, l'élément n'expirera jamais (mais le serveur de cache ne garantie pas que cet élément sera toujours stocké, il peut être effacé du cache pour faire de la place à d'autres éléments). Vous pouvez utiliser la constante MEMCACHE_COMPRESSED comme valeur du paramètre flag si vous voulez utiliser la compression à la volée (utilisation de la bibliothèque zlib).
Note: Souvenez-vous que les ressources (i.e. identifiant de fichiers ou de connexion) ne peuvent pas être stockées dans le cache, car elles ne peuvent pas être représentées linéairement.
Vous pouvez également utiliser la fonction memcache_set().
Liste de paramètres
- key
-
La clé qui sera associée avec l'élément.
- var
-
La variable à enregistrer. Les chaînes de caractères et les entiers sont enregistrés comme tels, les autres types sont enregistrés de manière sérialisée.
- flag
-
Utilisez MEMCACHE_COMPRESSED pour enregistrer l'élément compressé (utilise zlib).
- expire
-
Temps d'expiration pour l'élément. S'il égal 0, l'élément n'expirera jamais. Vous pouvez aussi utiliser un timestamp Unix ou un nombre de seconde en commençant par la date d'aujourd'hui, mais dans le dernier cas, le nombre de secondes ne doit pas excéder 2592000 (30 jours).
Valeurs de retour
Cette fonction retourne TRUE en cas de succès, FALSE en cas d'échec.
Exemples
Exemple #1 Exemple avec Memcache::set()
<?php
/* API procédurale */
/* connexion au serveur de cache */
$memcache_obj = memcache_connect('memcache_host', 11211);
/*
définie la valeur de l'élément identifié par la clé 'var_key' ;
utilisation de la valeur 0 pour le flag ;
la compression n'est pas utilisée ;
le délai d'expiration vaut 30 secondes
*/
memcache_set($memcache_obj, 'var_key', 'quelques variables', 0, 30);
echo memcache_get($memcache_obj, 'var_key');
?>
Exemple #2 Exemple avec Memcache::set()
<?php
/* API orientée objet */
$memcache_obj = new Memcache;
/* connexion au serveur de cache */
$memcache_obj->connect('memcache_host', 11211);
/*
définie la valeur de l'élément identifié par la clé 'var_key' ;
utilisation de la compression à la volée ;
le délai d'expiration vaut 50 secondes
*/
$memcache_obj->set('var_key', 'quelques grosses variables', MEMCACHE_COMPRESSED, 50);
echo $memcache_obj->get('var_key');
?>
Voir aussi
- Memcache::add() - Ajout d'un élément au serveur
- Memcache::replace() - Remplace une valeur d'un élément existant
Memcache::set
28-Oct-2008 08:03
07-Aug-2008 07:25
To expand on eseaberg's note somewhat, the connection is marked as failed on a *get* for an unserializable value on a key marked with the undocumented serialized flag. The initial assignment returns true. This is probably expected behavior, but I was confused when I forgot the flags argument and passed in 5 seconds for an expiration time.
<?php
$server = 'wwwdev.daz3d.com';
$m = new Memcache;
var_dump($m->connect($server));
var_dump($m->flush());
var_dump($m->set('foo', serialize('bar'), 1));
var_dump($m->get('foo'));
var_dump($m->set('foo', 'bar', 1));
var_dump($m->set('foo', 'baz'));
var_dump($m->get('foo')); // 'baz'
var_dump($m->set('foo', 'bar', 1));
var_dump($m->get('foo')); // false
var_dump($m->set('foo', 'bar'));
var_dump($m->connect($server));
var_dump($m->set('foo', 'bar'));
var_dump($m->get('foo'));
?>
25-Jun-2008 12:12
Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key. "get" may return any of the values.
This was tested on a multiple-server setup - behaviour may be different if you only have one server.
Remedy is to use a combination of replace and set:
$result = $memcache->replace( $key, $var );
if( $result == false )
{
$result = $memcache->set( $key, $var );
}
10-Jun-2008 10:00
"Other types are stored serialized" isn't true, at least as of PHP 5.2.0 with memcache extension $Revision: 1.85 $.
Null is serialized, but for an int, float, or bool, Memcache::set converts the value to a string (actually it tampers with the caller's zval, as if taking it by reference and using settype) and Memcache::get will return a string instead of the original type.
Using $memcache->set($key, serialize($var), 1) is a workaround. This undocumented bit in $flag tells Memcache::get to deserialize the value it reads. If this bit is set on a value that can't be deserialized, the server is marked as failed.
14-Apr-2008 02:45
The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).
09-Apr-2008 02:07
I ran into problems using the MEMCACHE_COMPRESSED flag when storing small amounts of data, such as an integers.
For expample.
Memcache::set('integer', 123456, MEMCACHE_COMPRESSED);
//would return true
Memcache::get('integer');
//would return false
This problem went away when I removed the MEMCACHE_COMPRESSED flag for values that were small.
24-Sep-2007 06:46
Here is a very visual example on how to use the memcache. It sets the key 'time' to the current time.
Put the example code in an empty page and keep reloading it.
As you can see, after 10 seconds your memcache key will be able to update with a new timestamp.
<?php
$memcache_obj = new Memcache;
$memcache_obj->connect('127.0.0.1', 11211);
if ($memcache_obj->get('time') == "") {
$date = date("H:i:s");
$memcache_obj->set('time', $date, MEMCACHE_COMPRESSED, 10);
}
echo "At ".date("H:i:s").", your key is ".$memcache_obj->get('time');
?>
19-Jul-2007 08:20
This is just two minor things about memcache that might not be perfectly clear, the limits on key and data sizes and what happen to flags in the memcache protocol.
* There is a max key size of 250 anything bigger gets truncated. There is also a (1MB - 42 bytes) limit on the data.
* In the memcache protocol there is a 16bit, 32bit in newer version, flag that you can set to whatever you want because memcache doesn't do anything with the flags. The php api doesn't let you get the flags because php uses the flags for php's own use such as "MEMCACHE_COMPRESSED" and I decided to test if it was doing something because it wasn't part of the memcache protocol.
<?php
$memcache = new Memcache();
$memcache->connect("127.0.0.1", 11211);
// Since memcache truncates the keys at 250 bytes both the get "250 a's" and "251 a's" will find the key in the cache
echo "*** Truncate key test ***<br>";
echo "set 251: " . ($memcache->set(str_repeat("a", 251), "value", 0, 1) ? "t" : "f") . "<br>";
echo "get 249: " . (($ret = $memcache->get(str_repeat("a", 249))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 250: " . (($ret = $memcache->get(str_repeat("a", 250))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 251: " . (($ret = $memcache->get(str_repeat("a", 251))) !== false ? "'$ret'" : "f") . "<br>";
echo "delete: " . ($memcache->delete(str_repeat("a", 250)) ? "t" : "f") . "<br><br>";
echo "*** Compress value test ***<br>";
echo "set 1024*1024-42: " . ($memcache->set("test", str_repeat("a", 1024*1024-42), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024-41: " . ($memcache->set("test", str_repeat("a", 1024*1024-41), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024 compressed: " . ($memcache->set("test", str_repeat("a", 1024*1024), MEMCACHE_COMPRESSED, 1) ? "t" : "f") . "<br>";
echo "delete: " . ($memcache->delete("test") ? "t" : "f") . "<br>";
$memcache->close();
?>
Output:
*** Truncate key test ***
set 251: t
get 249: f
get 250: 'value'
get 251: 'value'
delete: t
*** Compress value test ***
set 1024*1024-42: t
set 1024*1024-41: f
set 1024*1024 compressed: t
delete: t
