Skip to content

Commit 5f2f44c

Browse files
committed
add: 异步事件
1 parent fe8902d commit 5f2f44c

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/**
4+
* 创建监听器类
5+
* User: lisgroup
6+
* Date: 19-4-13
7+
* Time: 下午10:28
8+
*/
9+
10+
namespace App\Listeners;
11+
12+
use App\Tasks\TaskEvent;
13+
use Hhxsv5\LaravelS\Swoole\Task\Task;
14+
use Hhxsv5\LaravelS\Swoole\Task\Event;
15+
use Hhxsv5\LaravelS\Swoole\Task\Listener;
16+
17+
class TaskListener extends Listener
18+
{
19+
// 声明没有参数的构造函数
20+
public function __construct()
21+
{
22+
}
23+
24+
public function handle(Event $event)
25+
{
26+
\Log::info(__CLASS__.':handle start', [$event->getData()]);
27+
sleep(2);// 模拟一些慢速的事件处理
28+
// 监听器中也可以投递Task,但不支持Task的finish()回调。
29+
// 注意:
30+
// 1.参数2需传true
31+
// 2.config/laravels.php中修改配置 task_ipc_mode 为1或2,参考 https://wiki.swoole.com/wiki/page/296.html
32+
$ret = Task::deliver(new TaskEvent('task data'), true);
33+
var_dump($ret);
34+
// throw new \Exception('an exception');// handle时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
35+
}
36+
}

laravel/app/Tasks/TaskEvent.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
/**
3+
* 创建事件类--异步事件
4+
* 此特性依赖Swoole的AsyncTask,必须先设置config/laravels.php的swoole.task_worker_num。
5+
* 异步事件的处理能力受Task进程数影响,需合理设置task_worker_num。
6+
* User: lisgroup
7+
* Date: 19-4-13
8+
* Time: 下午10:23
9+
*/
10+
11+
namespace App\Tasks;
12+
13+
use Hhxsv5\LaravelS\Swoole\Task\Event;
14+
15+
class TaskEvent extends Event
16+
{
17+
private $data;
18+
19+
public function __construct($data)
20+
{
21+
$this->data = $data;
22+
}
23+
24+
public function getData()
25+
{
26+
return $this->data;
27+
}
28+
}

0 commit comments

Comments
 (0)