我们有一个网页想限制 uo 到 100 人可以同时访问,所以我们使用 memcached 来实现一个全局计数器,例如
我们正在使用 http://www.php.net/manual/en/class.memcache.php
所以没有 cas
,当前代码是这样的
$count = $memcache_obj->get('count');
if ($count < 100) {
$memcache_obj->set('count', $count+1);
echo "Welcome";
} else {
echo "No luck";
}
如您所见,上面的代码中存在竞争条件,但如果我们不打算替换支持 cas
的 memcached
扩展,它能够支持它仅使用 PHP 代码?
最佳答案
作为对“emcconville”的回答。即使没有 CAS,这也是非阻塞的。
如果您担心竞争条件,并且计数值完全是任意的,您可以在任何业务逻辑之前直接使用 Memcache::increment
。
increment方法将在递增发生后返回当前值;其中,您可以比较结果。如果尚未设置 key ,增量也将返回 false;允许您的应用程序根据需要处理它。
$current = $memcache_obj->increment('count');
if($current === false) {
// NOT_FOUND, so let's create it
// Will return false if has just been created by someone else.
$memcache_obj->add('count',0); // <-- no risk of race-condition
// At this point 'count' key is created by us or someone else (other server/process).
// "increment" will update 0 or whatever it is at the moment by 1.
$current = $memcache_obj->increment('count')
echo "You are the $current!";
}
if ($current < 100) {
echo "Hazah! You are under the limit. Congrats!";
} else {
echo "Ah Snap! No Luck - you reached the limit.";
// If your worried about the value growing _too_ big, just drop the value down.
// $memcache_obj->decrement('count');
}
关于php - 在不使用 cas 的情况下在 Memcached 中实现原子计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13132664/