namespace EasySwoole\Actor\Test;
use EasySwoole\Actor\AbstractActor;
use EasySwoole\Actor\ActorConfig;
class RoomActor extends AbstractActor
{
public static function configure(ActorConfig $actorConfig)
{
$actorConfig->setActorName('Room');
}
public function onStart()
{
//每当一个RoomActor实体被创建的时候,都会执行该回调
var_dump('room actor '.$this->actorId().' start');
}
public function onMessage($msg)
{
//每当一个RoomActor实体收到外部消息的时候,都会执行该回调当
var_dump('room actor '.$this->actorId().' onmessage: '.$msg);
return 'reply at '.time();
}
public function onExit($arg)
{
//每当一个RoomActor实体退出的时候,都会执行该回调
var_dump('room actor '.$this->actorId().' exit at arg: '.$arg);
return 'exit at '.time();
}
protected function onException(\Throwable $throwable)
{
//每当一个RoomActor出现异常的时候,都会执行该回调
var_dump($throwable->getMessage());
}
}
在cli模式下创建一个Actor服务
use EasySwoole\Actor\Actor;
use EasySwoole\Actor\Test\RoomActor;
use EasySwoole\Actor\ProxyProcess;
Actor::getInstance()->register(RoomActor::class);
$list = Actor::getInstance()->generateProcess();
foreach ($list['proxy'] as $proxy){
/** @var ProxyProcess $proxy */
$proxy->getProcess()->start();
}
foreach ($list['worker'] as $actors){
foreach ($actors as $actorProcess){
/** @var ProxyProcess $actorProcess */
$actorProcess->getProcess()->start();
}
}
while($ret = \Swoole\Process::wait()) {
echo "PID={$ret['pid']}\n";
}
创建一个cli测试脚本
use EasySwoole\Actor\Actor;
use EasySwoole\Actor\Test\RoomActor;
Actor::getInstance()->register(RoomActor::class);
go(function (){
$actorId = RoomActor::client()->create('create arg1');
var_dump($actorId);
\co::sleep(3);
var_dump(RoomActor::client()->send($actorId,'this is msg'));
\co::sleep(3);
var_dump(RoomActor::client()->exit($actorId,'this is exit arg'));
\co::sleep(3);
RoomActor::client()->create('create arg2');
\co::sleep(3);
RoomActor::client()->create('create arg3');
\co::sleep(3);
var_dump(RoomActor::client()->sendAll('sendAll msg'));
\co::sleep(3);
var_dump(RoomActor::client()->status());
\co::sleep(3);
var_dump(RoomActor::client()->exitAll('sendAll exit'));
});
以上代码执行结果如下:
服务端
php test.php
string(40) "room actor 00101000000000000000001 start"
string(57) "room actor 00101000000000000000001 onmessage: this is msg"
string(64) "room actor 00101000000000000000001 exit at arg: this is exit arg"
string(40) "room actor 00101000000000000000002 start"
string(40) "room actor 00103000000000000000001 start"
string(57) "room actor 00101000000000000000002 onmessage: sendAll msg"
string(57) "room actor 00103000000000000000001 onmessage: sendAll msg"
string(60) "room actor 00101000000000000000002 exit at arg: sendAll exit"
string(60) "room actor 00103000000000000000001 exit at arg: sendAll exit"