这篇文章给大家分享的内容是关于swoft 源码剖析之swoole和swoft的一些介绍(task投递/定时任务篇),有一定的参考价值,有需要的朋友可以参考一下。
swoft的任务功能基于swoole的task机制,或者说swoft的task机制本质就是对swoole的task机制的封装和加强。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//swoft\task\task.php
class task
{
/**
* deliver coroutine or async task
*
* @param string $taskname
* @param string $methodname
* @param array $params
* @param string $type
* @param int $timeout
*
* @return bool|array
* @throws taskexception
*/
public static function deliver(string $taskname, string $methodname, array $params = [], string $type = lf::type_co, $timeout = 3)
{
$data = taskhelper::pack($taskname, $methodname, $params, $type);
if(!app::isworkerstatus() && !app::iscocontext()){
return lf::deliverbyqueue($data);//见下文command章节
}
if(!app::isworkerstatus() && app::iscocontext()){
throw new taskexception('plea deliver task by http!');
}
$rver = app::$rver->getrver();
// delier coroutine task
if ($type == lf::type_co) {
$tasks[0] = $data;
$priflekey = 'task' . '.' . $taskname . '.' . $methodname;
app::profilestart($priflekey);
$r点读笔推荐esult = $rver->taskco($tasks, $timeout);
app::profileend($priflekey);
return $result;
}
// deliver async task
return $rver->task($data);
}
}
任务投递task::deliver()将调用参数打包后根据$type参数通过swoole的$rver->taskco()或$rver->task()接口投递到task进程。task本身始终是同步执行的,$type仅仅影响投递这一操作的行为,task::type_async对应的$rver->task()是异步投递,task::deliver()调用后马上返回;task::type_co对应的$rver->taskco()是协程投递,投递后让出协程控制,任务完成或执行超时后task::deliver()才从协程返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//swoft\task\bootstrap\listeners\taskeventlistener
/**
* the list反复的作用ener of swoole task
* @swoolelistener({
* swooleevent::on_task,
* swooleevent::on_finish,
* })
*/
class taskeventlistener implements taskinterface, finishinterface
{
/**
* @param \swoole\rver $rver
* @param int $taskid
* @param int $workerid
* @param mixed $data
* @return mixed
* @throws \invalidargumentexception
*/
public function ontask(rver $rver, int $taskid, int $workerid, $data)
{
try {
/* @var taskexecutor $taskexecutor*/
$taskexecutor = app::getbean(taskexecutor::class);
$result = $taskexecutor->run($data);
} catch (\throwable $throwable) {
app::error(sprintf('taskexecutor->run %s file=%s line=%d ', $throwable->getmessage(), $throwable->getfile(), $throwable->getline()));
$result = fal;
// relea system resources
app::trigger(appevent::resource_relea);
app::trigger(taskevent::after_task);
}
return $result;
}
}
此处是swoole.ontask的事件回调,其职责仅仅是将将worker进程投递来的打包后的数据转发给taskexecutor。
swoole的task机制的本质是worker进程将耗时任务投递给同步的task进程(又名taskworker)处理,所以swoole.ontask的事件回调是在task进程中执行的。上文说过,worker进程是你大部分http服务代码执行的环境,但是从taskeventlistener.ontask()方法开始,代码的执行环境都是task进程,也就是说,taskexecutor和具体的taskbean都是执行在task进程中的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//swoft\task\taskexecutor
/**
* the task executor
*
* @bean()
*/
class taskexecutor
{
/**
* @param string $data
* @return mixed
*/
public function run(string $data)
{
$data = taskhelper::unpack($data);
$name = $data['name'];
$type = $data['type'];
$method = $data['method'];
$params = $data['params'];
$logid = $data['logid'] ?? uniqid('', true);
$spanid = $data['spanid'] ?? 0;
$collector = taskcollector::getcollector();
if (!ist($collector['task'][$name])) {
return fal;
}
list(, $coroutine) = $collector['task'][$name];
$task = app::getbean($name);
if ($coroutine) {
$result = $this->runcotask($task, $method, $params, $logid, $spanid, $name, $type);
} el {
$result = $this->runsynctask($task, $method, $params, $logid, $spanid, $name, $type);
}
return $result;
}
}
任务执行思路很简单,将worker进程发过来的数据解包还原成原来的调用参数,根据$name参数找到对应的taskbean并调用其对应的task()方法。其中taskbean使用类级别注解@task(name="taskname")或者@task("taskname")声明。
值得一提的一点是,@task注解除了name属性,还有一个coroutine属性,上述代码会根据该参数选择使用协程的runcotask()或者同步的runsynctask()执行task。但是由于而且由于swoole的task进程的执行是完全同步的,不支持协程,所以目前版本请该参数不要配置为true。同样的在taskbean中编写的任务代码必须的同步阻塞的或者是要能根据环境自动将异步非阻塞和协程降级为同步阻塞的
前面我们提到:
swoole的task机制的本质是worker进程将耗时任务投递给同步的task进程(又名taskworker)处理。
换句话说,swoole的$rver->taskco()或$rver->task()都只能在worker进程中使用。
这个限制大大的限制了使用场景。 如何能够为了能够在process中投递任务呢?swoft为了绕过这个限制提供了task::deliverbyprocess()方法。其实现原理也很简单,通过swoole的$rver->ndmessage()方法将调用信息从process中投递到worker进程中,然后由worker进程替其投递到task进程当中,相关代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//swoft\task\task.php
/**
* deliver task by process
*
* @param string $taskname
* @param string $methodname
* @param array $params
* @param string $type
* @param int $timeout
* @param int $workid
*
* @return bool
*/
public static function deliverbyprocess(string $taskname, string $methodname, array $params = [], int $timeout = 3, int $workid = 0, string $type = lf::type_async): bool
{
/* @var pipemessageinterface $pipemessage */
$rver = app::$rver->getrver();
$pipemessage = app::getbean(pipemessage::class);
$data = [
'name' => $taskname,
'method' => $methodname,
'params' => $params,
'timeout' => $timeout,
'type' => $type,
];
$message = $pipemessage->pack(pipemessage::message_type_task, $data);
return $rver->ndmessage($message, $workid);
}
数据打包后使用$rver->ndmessage()投递给worker:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//swoft\bootstrap\rver\rvertrait.php
/**
* onpipemessage event callback
*
* @param \swoole\rver $rver
* @param int $srcworkerid
* @param string $message
* @return void
* @throws \invalidargumentexception
*/
public function onpipemessage(rver $rver, int $srcworkerid, string $message)
{
/* @var pipemessageinterface $pipemessage */
$pipemessage = app::getbean(pipemessage::class);
list($type, $data) = $pipemessage->unpack($message);
修身齐家治国平天下什么意思app::trigger(appevent::pipe_message, null, $type, $data, $srcworkerid);
}
$rver->ndmessage后,worker进程收到数据时会触发一个swoole.pipemessage事件的回调,swoft会将其转换成自己的swoft.pipemessage事件并触发.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//swoft\task\event\listeners\pipemessagelistener.php
/**
* the pipe message listener
*
* @listener(event=appevent::pipe_message)
*/
class pipemessagelistener implements eventhandlerinterface
{
/**
* @param \swoft\event\eventinterface $event
*/
public function handle(eventinterface $event)
{
$params = $event->getparams();
if (count($params) < 3) {
return;
}
list($type, $data, $srcworkerid) = $params;
if ($type != pipemessage::message_type_task) {
return;
}
$type = $data['type'];
$taskname = $data['name'];
$params = $data['params'];
$timeout = $data['timeout'];
$methodname = $data['method'];
// delever task
task::deliver($taskname, $methodname, $params, $type, $timeout);
}
}
swoft.pipemessage事件最终由pipemessagelistener处理。在相关的监听其中,如果发现swoft.pipemessage事件由task::deliverbyprocess()产生的,worker进程会替其执行一次task::deliver(),最终将任务数据投递到taskworker进程中。
一道简单的回顾练习:从task::deliverbyprocess()到某taskbean最终执行任务,经历了哪些进程,而调用链的哪些部分又分别是在哪些进程中执行?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//swoft\task\queuetask.php
/**
* @param string $data
* @param int $taskworkerid
* @param int $srcworkerid
*
* @return bool
*/
public function deliver(string $data, int $taskworkerid = null, $srcworkerid = null)
{
if ($taskworkerid === null) {
$taskworkerid = mt_rand($this->workernum + 1, $this->workernum + $this->tasknum);
}
if ($srcworkerid === null) {
$srcworkerid = mt_rand(0, $this->workernum - 1);
}
$this->check();
$data = $this->pack($data, $srcworkerid);
$result = \msg_nd($this->queueid, $taskworkerid, $data, fal);
if (!$result) {
return fal;
}
return true;
}
对于command进程的任务投递,情况会更复杂一点。
上文提到的process,其往往衍生于http/rpc服务,作为同一个manager的子孙进程,他们能够拿到swoole\rver的句柄变量,从而通过$rver->ndmessage(),$rver->task()等方法进行任务投递。
但在swoft的体系中,还有一个十分路人的角色:command。command的进程从shell或cronb独立启动,和http/rpc服务相关的进程没有亲缘关系。因此command进程以及从command中启动的process进程是没有办法拿到swoole\rver的调用句柄直接通过unixsocket进行任务投递的。
为了为这种进程提供任务投递支持,swoft利用了swoole的task进程的一个特殊功能—-消息队列。
同一个项目中command和http\rpcrver通过约定一个message_queue_key获取到系统内核中的同一条消息队列,然后comand进程就可以通过该消息队列向task进程投递任务了。
该机制没有提供对外的公开方法,仅仅被包含在task::deliver()方法中,swoft会根据当前环境隐式切换投递方式。但该消息队列的实现依赖maphore拓展,如果你想使用,需要在编译php时加上--enable-sysvmsg参数。
除了手动执行的普通任务,swoft还提供了精度为秒的定时任务功能用来在项目中替代linux的crontab功能.
swoft用两个前置process—任务计划进程:crontimerprocess和任务执行进程cronexecprocess
,和两张内存数据表—–runtimetable(任务(配置)表)origintable((任务)执行表)用于定时任务的管理调度。
两张表的每行记录的结构如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
\\swoft\task\crontab\tablecrontab.php
/**
* 任务表,记录用户配置的任务信息
* 表每行记录包含的字段如下,其中`rule`,`taskclass`,`taskmethod`生成key唯一确定一条记录
* @var array $originstruct
*/
private $originstruct = [
'rule' => [\swoole\table::type_string, 100],//定时任务执行规则,对应@scheduled注解的cron属性
'taskclass' => [\swoole\table::type_string, 255],//任务名 对应@task的name属性(默认为类名)
'taskmethod' => [\swoole\table::type_string, 255],//task方法,对应@scheduled注解所在方法
'add_time' => [\swoole\table::type_string, 11],//初始化该表内容时的10位时间戳
];
/**
* 执行表,记录短时间内要执行的任务列表及其执行状态
* 表每行记录包含的字段如下,其中`taskclass`,`taskmethod`,`minute`,`c`生成key唯一确定一条记录
* @var array $runtimestruct
*/
private $runtimestruct = [
'taskclass' => [\swoole\table::type_string, 255],//同上
'taskmethod' => [\swoole\table::type_string, 255],//同上
'minute' => [\swoole\table::type_string, 20],//需要执行任务的时间,精确到分钟 格式date('ymdhi')
'c' => [\swoole\table::type_string, 20],//需要执行任务的时间,精确到分钟 10位时间戳
'runstatus' => [\swoole\table::type_int, 4],//任务状态,有 0(未执行) 1(已执行) 2(执行中) 三种。
//注意:这里的执行是一个容易误解的地方,此处的执行并不是指任务本身的执行,而是值`任务投递`这一操作的执行,从宏观上看换成 _未投递_,_已投递_,_投递中_描述会更准确。
];
swoft的的定时任务管理是分别由任务计划进程和任务执行进程进程负责的。两个进程的运行共同管理定时任务,如果使用进程间独立的array()等结构,两个进程必然需要频繁的进程间通信。而使用跨进程的table(本文的table,除非特别说明,都指swoole的swoole\table结构)直接进行进程间数据共享,不仅性能高,操作简单 还解耦了两个进程。
为了table能够在两个进程间共同使用,table必须在swoole rver启动前创建并分配内存。具体代码在swoft\task\bootstrap\listeners->onbeforestart()中,比较简单,有兴趣的可以自行阅读。
背景介绍完了,我们来看看这两个定时任务进程的行为
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//swoft\task\bootstrap\process\crontimerprocess.php
/**
* crontab timer process
*
* @process(name="crontimer", boo663t=true)
*/
class crontimerprocess implements processinterface
{
/**
* @param \swoft\process\process $process
*/
public function run(swoftprocess $process)
{
//code....
/* @var \swoft\task\crontab\crontab $cron*/
$cron = app::getbean('crontab');
// swoole/httprver
$rver = app::$rver->getrver();
$time = (60 - date('s')) * 1000;
$rver->after($time, function () u ($rver, $cron) {
// every minute check all tasks, and prepare the tasks that next execution point needs
$cron->checktask();
$rver->tick(60 * 1000, function () u ($cron) {
$cron->checktask();
});
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//swoft\task\crontab\crontab.php
/**
* 初始化runtimetable数据
*
* @param array $task 任务
* @param array $parresult 解析crontab命令规则结果,即task需要在当前分钟内的哪些秒执行
* @return bool
*/
private function initruntimetabledata(array $task, array $parresult): bool
{
$runtimetabletasks = $this->getruntimetable()->table;
$min = date('ymdhi');
$c = strtotime(date('y-m-d h:i'));
foreach ($parresult as $time) {
$this->checktaskqueue(fal);
$key = $this->getkey($task['rule'], $task['taskclass'], $task['taskmethod'], $min, $高考英语作文万能模板time + $c);
$runtimetabletasks->t($key, [
'taskclass' => $task['taskclass'],
'taskmethod' => $task['taskmethod'],
'minute' => $min,
'c' => $time + $c,
'runstatus' => lf::normal
]);
}
return true;
}
crontimerprocess是swoft的定时任务调度进程,其核心方法是crontab->initruntimetabledata()。
该进程使用了swoole的定时器功能,通过swoole\timer在每分钟首秒时执行的回调,crontimerprocess每次被唤醒后都会遍历任务表计算出当前这一分钟内的60秒分别需要执行的任务清单,写入执行表并标记为 未执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//swoft\task\bootstrap\process
/**
* crontab process
*
* @process(name="cronexec", boot=true)
*/
class cronexecprocess implements processinterface
{
/**
* @param \swoft\process\process $process
*/
public function run(swoftprocess $process)
{
$pname = app::$rver->getpname();
$process->name(sprintf('%s cronexec process', $pname));
/** @var \swoft\task\crontab\crontab $cron */
$cron = app::getbean('crontab');
// swoole/httprver
$rver = app::$rver->getrver();
$rver->tick(0.5 * 1000, function () u ($cron) {
$tasks = $cron->getexectasks();
if (!empty($tasks)) {
foreach ($tasks as $task) {
// diliver task
task::deliverbyprocess($task['taskclass'], $task['taskmethod']);
$cron->finishtask($task['key']);
}
}
});
}
}
cronexecprocess作为定时任务的执行者,通过swoole\timer每0.5s唤醒自身一次,然后把执行表遍历一次,挑选当下需要执行的任务,通过ndmessage()投递出去并更新该 任务执行表中的状态。
该执行进程只负责任务的投递,任务的实际实际执行仍然在task进程中由taskexecutor处理。
本文发布于:2023-04-07 20:20:24,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/8c155258821d46ad92efe417d0bcb4c1.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Swoft源码之Swoole和Swoft的分析.doc
本文 PDF 下载地址:Swoft源码之Swoole和Swoft的分析.pdf
| 留言与评论(共有 0 条评论) |