配置
$serv = new swoole_server("127.0.0.1", 9501);
$serv->set(array(
'worker_num' => 4,
'task_worker_num' => 8,
));
啟動
$serv->on('workerStart', function($serv, $worker_id) {
//處理訂單
$redis = new redis;
$redis->connect('127.0.0.1', 6379);
$serv->redis = $redis;
if($worker_id == 0){
swoole_timer_tick(500, function ($timer_id) use($serv,$worker_id) {
$serv->task('queue');
});
}
});
$serv->start();
Task非同步處理任務
簡單邏輯示例,具體根據實際業務情況處理
$serv->on('Task', function (swoole_server $serv, $task_id, $from_id, $data) {
$redis = $serv->redis;
$orders = $redis->lrange('queue',0,-1);
foreach ($orders as $i => $order){
$info = json_decode($order, true);
if(empty($info)){
break;
}
*** ...訂單處理邏輯... ***
//處理完成,刪除
$redis->lTrim('queue', 1, -1);
}
$serv->finish($data);
});
其他
$serv->on('receive', function (swoole_server $serv, $fd, $reactor_id, $data) {
});
$serv->on('Finish', function (swoole_server $serv, $task_id, $data) {
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結