PHP Atomic Memcache

Kov*_*ovo 2 php memcached

我想知道在我的网络应用程序中使我的Memcache操作atmoic的最佳方法是什么.

考虑以下场景:

Client 1 connects and retrieves data from key 1
Client 2 connects a few microsecond after Client 1, requests the same data from key 1
Client 1 saves new data to key 1
Client 2 saves new (different data) to key 1, not taking into account that Client 1 modified the value already
Run Code Online (Sandbox Code Playgroud)

在这种情况下,过程中没有原子性.

我的(潜在)解决方案是在我的应用程序中设置,获取和释放键上的锁.

因此,在我执行之后,上面的过程会像这样工作:

Client 1 connects, checks for an active lock on key 1, finds none, and gets the data
Client 2 connects a few microsecond after Client 1, requests the same data from key 1, but finds a lock
Client 2 enters a retry loop until Client 1 releases the lock
Client 1 saves new data to key 1, releases the lock
Client 2 gets the fresh data, sets a lock on key 1, and continues
Run Code Online (Sandbox Code Playgroud)

思考?这种方法是否有效,是否会有任何性能点击我应该警惕?

Fra*_*ila 5

考虑一下你在这里要解决的问题.你呢:

  1. 只是想避免丢失更新问题.(例如,计数器增加1.)
  2. 或者你需要确保,虽然一个客户端已经检索的项的值,没有其他客户端可以使用该值?(这是值代表有限资源的地方.)

大多数时候人们只是想要(1).如果这就是你想要的,你可以使用check-and-set语义Memcached::cas(),或者如果你有一个简单的整数值,你可以使用原子Memcached::increment()Memcached::decrement()操作.

但是,如果需要使用密钥来表示有限资源(2),请考虑使用一组不同的语义:

$keyname = 'key_with_known_name_representing_finite_resource';

// try to "acquire" the key with add().
// If the key exists already (resource taken), operation will fail
// otherwise, we use it then release it with delete()
// specify a timeout to avoid a deadlock.
// timeout should be <= php's max_execution_time
if ($mcache->add($keyname, '', 60)) {
   // resource acquired
   // ...do stuff....
   // now release
   $mcache->delete($keyname);
} else {
   // try again?
}
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因您无法访问cas(),可以使用两个键实现锁定和add()/delete

$key = 'lockable_key_name';
$lockkey = $key.'##LOCK';

if ($mcache->add($lockkey, '', 60)) { // acquire
    $storedvalue = $mcache->get($key);
    // do something with $storedvalue
    $mcache->set($key, $newvalue);
    // release
    $mcache->delete($lockkey);
}
Run Code Online (Sandbox Code Playgroud)

与检查和设置方法相比,这种方法会导致更多的资源争用.

  • 最好的解决方案是`cas()`.第二个最好的解决方案是使用两个键:`$ keyname`和`$ keyname .'_ lock'`.使用`add()/ delete()`来获取/释放锁. (2认同)