使用swoole實現異步任務處理,有如下幾個目標:php
swoole內置的swoole_http_server正好很是適合處理這種業務,示例代碼實現以下node
php#!/bin/env php <?php $http = new swoole_http_server("0.0.0.0", 9501); //redis 存儲任務處理結果和進度 $redis = new \Redis(); $redis->connect("127.0.0.1", 6379); $http->set([ 'worker_num' => 2, 'open_tcp_nodelay' => true, 'task_worker_num' => 2, 'daemonize' => true, 'log_file' => '/tmp/swoole_http_server.log', ]); $http->on('request', function(swoole_http_request $request, swoole_http_response $response) use ($http, $redis) { //請求過濾 if($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico'){ return $response->end(); } $taskId = isset($request->get['taskId']) ? $request->get['taskId']: ''; if($taskId !== ''){ //返回任務狀態 $status = $redis->get($taskId); return $response->end("task: $taskId;status: $status"); } $params = json_encode(array(111,222));//此到處理requst請求數據做爲任務執行的數據,根據須要修改 $taskId = $http->task($params); $response->end(" <h1>Do task:$taskId.</h1> "); }); $http->on('Finish', function($serv, $taskId, $data){ //TDDO 任務結束以後處理任務或者回調 echo "$taskId task finish"; }); $http->on('task', function($serv, $taskId, $fromId, $data) use($redis){ //任務處理,能夠把處理結果和狀態在redis裏面實時更新,便於獲取任務狀態 for($i = 0; $i < 100;$i++){ $redis->set($taskId, $i); sleep(1); } return $i;//必須有return 不然不會調用onFinish }); $http->start();
若有更好方案,請多多指教。redis