PHP下用Swoole实现Actor并发模型的方法(2)
在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"
客户端
php test2.php
string(23) "00101000000000000000001"
string(19) "reply at 1559623925"
string(18) "exit at 1559623928"
bool(true)
array(3) {
[1]=>
int(1)
[2]=>
int(0)
[3]=>
int(1)
}
bool(true)
更多细节可以在EasySwoole项目官网得到文档支持 http://easyswoole.com/
喜欢EasySwoole项目的,可以给个star https://github.com/easy-swoole/easyswoole
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
