Context上下文管理器
在Swoole
中,由于多個協程是并發執行的,因此不能使用類靜態變量/全局變量保存協程上下文內容。使用局部變量是安全的,因為局部變量的值會自動保存在協程棧中,其他協程訪問不到協程的局部變量。
因Swoole
屬于常駐內存,在特殊情況下聲明變量,需要進行手動釋放,釋放不及時,會導致非常大的內存開銷,使服務宕掉。
ContextManager
上下文管理器存儲變量會自動釋放內存,避免開發者不小心而導致的內存增長。
原理
- 通過當前協程
id
以key
來存儲該變量。 - 注冊
defer
函數。 - 協程退出時,底層自動觸發
defer
進行回收。
安裝
EasySwoole
默認加載該組件,無須開發者引入。在非EasySwoole
框架中使用,開發者可自行引入。
composer require easyswoole/component
基礎例子
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");
});
以上利用上下文管理器來實現協程上下文的隔離。
自定義處理項
例如,當有一個key,希望在協程環境中,get的時候執行一次創建,在協程退出的時候可以進行回收,就可以注冊一個上下文處理項來實現。該場景可以用于協程內數據庫短連接管理。
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');
});