Context上下文管理器
在Swoole中,由于多個(gè)協(xié)程是并發(fā)執(zhí)行的,因此不能使用類靜態(tài)變量/全局變量保存協(xié)程上下文內(nèi)容。使用局部變量是安全的,因?yàn)榫植孔兞康闹禃?huì)自動(dòng)保存在協(xié)程棧中,其他協(xié)程訪問不到協(xié)程的局部變量。
因Swoole屬于常駐內(nèi)存,在特殊情況下聲明變量,需要進(jìn)行手動(dòng)釋放,釋放不及時(shí),會(huì)導(dǎo)致非常大的內(nèi)存開銷,使服務(wù)宕掉。
ContextManager上下文管理器存儲(chǔ)變量會(huì)自動(dòng)釋放內(nèi)存,避免開發(fā)者不小心而導(dǎo)致的內(nèi)存增長。
原理
- 通過當(dāng)前協(xié)程
id以key來存儲(chǔ)該變量。 - 注冊(cè)
defer函數(shù)。 - 協(xié)程退出時(shí),底層自動(dòng)觸發(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");
});
以上利用上下文管理器來實(shí)現(xiàn)協(xié)程上下文的隔離。
自定義處理項(xiàng)
例如,當(dāng)有一個(gè)key,希望在協(xié)程環(huán)境中,get的時(shí)候執(zhí)行一次創(chuàng)建,在協(xié)程退出的時(shí)候可以進(jìn)行回收,就可以注冊(cè)一個(gè)上下文處理項(xiàng)來實(shí)現(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');
});