Key may not exceed 250 chars according to memcached protocol.
Memcache::add
(PECL memcache:0.2-2.1.2)
Memcache::add — サーバに項目を追加する
説明
Memcache::add() は、サーバに同名のキーが存在しない 場合に限り、key というキーで 値 var を格納します。 memcache_add() 関数を使用することも可能です。
パラメータ
- key
-
項目に関連付けられたキー。
- var
-
格納する値。文字列および整数値はそのままの形式で、それ以外の型は シリアライズされて格納されます。
- flag
-
項目を圧縮して格納する場合に MEMCACHE_COMPRESSED を使用します (zlib を使用します)。
- expire
-
項目の有効期限。ゼロの場合は有効期限なし (いつまでも有効) となります。Unix タイムスタンプ形式、あるいは現在からの 秒数で指定することが可能ですが、後者の場合は秒数が 2592000 (30 日) を超えることはできません。
返り値
成功した場合に TRUE を、失敗した場合に FALSE を返します。 もし同名のキーが既に存在する場合は FALSE を返します。 それ以外は、Memcache::add() の振る舞いは Memcache::set() と同じです。
例
例1 Memcache::add() の例
<?php
$memcache_obj = memcache_connect("localhost", 11211);
/* 手続き型の API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);
/* オブジェクト指向の API */
$memcache_obj->add('var_key', 'test variable', false, 30);
?>
Memcache::add
rune(at)intermedia(dot)no
06-Oct-2008 09:04
06-Oct-2008 09:04
php at tapirpirates dot net
03-Apr-2008 07:32
03-Apr-2008 07: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-Jun-2007 08:13
18-Jun-2007 08:13
if you read source code for MMC_SERIALIZED you will see at line ~1555 that only !(is_string,is_long,is_double,is_bool) are serialized
and that serialized values are flaged as MMC_SERIALIZED for return (fetch) code unserialize these values again
