$ip = $request->getRealIp();
$key =(string) ip2long($ip);
Cache::Incr($key); //1 //再次刷新 3
Locker::lock($key); //無(wú)鎖則加鎖繼續(xù) //已經(jīng)加鎖了 阻塞失敗
Cache::Incr($key); //2 //這里是4
return Cache::Get($key); //輸出2 //輸出4,甚至是5 鎖失效..
瀏覽器打開(kāi)接口然后一直點(diǎn)刷新..
Workerman/5.1.3 PHP/8.3.21 (JIT off) Darwin/23.6.0
--------------------- WORKERS ----------------------
event-loop proto user worker listen count state
fiber tcp lsmir2 webman http://0.0.0.0:8787 2 [OK]
event tcp lsmir2 monitor none 1 [OK]
event tcp lsmir2 plugin.webman.redis-queue.consumer none 2 [OK]
手搓一個(gè)多進(jìn)程鎖 感謝兔子大佬的WebmanSharedCache插件真的很好用.
<?php
namespace app\common;
use Workbunny\WebmanSharedCache\Cache;
class Locker
{
/**
* 多進(jìn)程鎖
* @param string $key 鎖的鍵名
* @param int $ttl 鎖過(guò)期時(shí)間,單位秒
* @return bool
*/
public static function lock(string $key, int $ttl = 2): bool
{
$lockKey = "lock_{$key}";
if (!Cache::get($lockKey)) {
Cache::set($lockKey, 1, ['EX' => $ttl]);
return true;
}
return false;
}
/**
* Unlock.
*
* @param string $key
* @return bool
*/
public static function unlock(string $key): bool
{
$lockKey = "lock_{$key}";
if (Cache::get($lockKey)) {
Cache::Del($lockKey);
return true;
}
return false;
}
}
Windows環(huán)境下locker不生效的, 需要在linux下進(jìn)行測(cè)試
具體看這個(gè): http://www.wtbis.cn/q/10238