Context上下文管理器
在Swoole
中,由于多個協(xié)程是并發(fā)執(zhí)行的,因此不能使用類靜態(tài)變量/全局變量保存協(xié)程上下文內(nèi)容。使用局部變量是安全的,因為局部變量的值會自動保存在協(xié)程棧中,其他協(xié)程訪問不到協(xié)程的局部變量。
因Swoole
屬于常駐內(nèi)存,在特殊情況下聲明變量,需要進(jìn)行手動釋放,釋放不及時,會導(dǎo)致非常大的內(nèi)存開銷,使服務(wù)宕掉。
ContextManager
上下文管理器存儲變量會自動釋放內(nèi)存,避免開發(fā)者不小心而導(dǎo)致的內(nèi)存增長。
原理
- 通過當(dāng)前協(xié)程
id
以key
來存儲該變量。 - 注冊
defer
函數(shù)。 - 協(xié)程退出時,底層自動觸發(fā)
defer
進(jìn)行回收。
安裝
EasySwoole
默認(rèn)加載該組件,無須開發(fā)者引入。在非EasySwoole
框架中使用,開發(fā)者可自行引入。
composer require easyswoole/component
基礎(chǔ)例子
use EasySwoole\Component\Context\ContextManager;
go(function (){
ContextManager::getInstance()->set('key','key in parent');
go(function (){
ContextManager::getInstance()->set('key','key in sub');
var_dump(ContextManager::getInstance()->get('key')." in");
});
\co::sleep(1);
var_dump(ContextManager::getInstance()->get('key')." out");
});
以上利用上下文管理器來實現(xiàn)協(xié)程上下文的隔離。
自定義處理項
例如,當(dāng)有一個key,希望在協(xié)程環(huán)境中,get的時候執(zhí)行一次創(chuàng)建,在協(xié)程退出的時候可以進(jìn)行回收,就可以注冊一個上下文處理項來實現(xiàn)。該場景可以用于協(xié)程內(nèi)數(shù)據(jù)庫短連接管理。
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\Component\Context\ContextItemHandlerInterface;
class Handler implements ContextItemHandlerInterface
{
function onContextCreate()
{
$class = new \stdClass();
$class->time = time();
return $class;
}
function onDestroy($context)
{
var_dump($context);
}
}
ContextManager::getInstance()->registerItemHandler('key',new Handler());
go(function (){
go(function (){
ContextManager::getInstance()->get('key');
});
\co::sleep(1);
ContextManager::getInstance()->get('key');
});