SwooleTask.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\Api\OrderService;
  4. use App\Services\Common\PayOrdersService;
  5. use App\Services\RedisService;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Support\Facades\DB;
  8. class SwooleTask extends Command
  9. {
  10. protected $serv;
  11. protected $host = '127.0.0.1';
  12. protected $port = 6670;
  13. // 进程名称
  14. protected $taskName = 'swooleTask';
  15. // PID路径
  16. protected $pidPath = '/storage/swoole.pid';
  17. // task
  18. protected $onlyReloadTaskWorker = false;
  19. // 设置运行时参数
  20. protected $options = [
  21. 'worker_num' => 8, //worker进程数,一般设置为CPU数的1-4倍
  22. 'daemonize' => true, //启用守护进程
  23. 'log_file' => '/storage/logs/swoole-task.log', //指定swoole错误日志文件
  24. 'log_level' => 5, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
  25. 'dispatch_mode' => 1, //数据包分发策略,1-轮询模式
  26. 'task_worker_num' => 6, //task进程的数量
  27. 'task_ipc_mode' => 3, //使用消息队列通信,并设置为争抢模式
  28. ];
  29. /**
  30. * The name and signature of the console command.
  31. *
  32. * @var string
  33. */
  34. protected $signature = 'swoole:task {op}';
  35. /**
  36. * The console command description.
  37. *
  38. * @var string
  39. */
  40. protected $description = 'Swoole task server description';
  41. /**
  42. * Create a new command instance.
  43. *
  44. * @return void
  45. */
  46. public function __construct()
  47. {
  48. parent::__construct();
  49. }
  50. /**
  51. * 入口
  52. * Execute the console command.
  53. *
  54. * @return mixed
  55. */
  56. public function handle()
  57. {
  58. ini_set("default_socket_timeout", -1);
  59. // 项目根目录
  60. defined('ROOT_PATH') or define('ROOT_PATH', base_path());
  61. // 文件上传目录
  62. defined('ATTACHMENT_PATH') or define('ATTACHMENT_PATH', base_path('public/uploads'));
  63. // 图片上传目录
  64. defined('IMG_PATH') or define('IMG_PATH', base_path('public/uploads/images'));
  65. // 临时存放目录
  66. defined('UPLOAD_TEMP_PATH') or define('UPLOAD_TEMP_PATH', ATTACHMENT_PATH . "/temp");
  67. // 定义普通图片域名
  68. defined('IMG_URL') or define('IMG_URL', env('IMG_URL'));
  69. // 数据表前缀
  70. defined('DB_PREFIX') or define('DB_PREFIX', DB::connection()->getTablePrefix());
  71. $this->options['log_file'] = base_path() . $this->options['log_file'];
  72. $this->pidPath = base_path() . $this->pidPath;
  73. $op = $this->argument('op');
  74. switch ($op) {
  75. case 'status': // 状态
  76. $res = $this->status();
  77. echo $res ? $res : 0;
  78. break;
  79. case 'start': // 运行
  80. return $this->start();
  81. break;
  82. case 'reload': // 平滑重启
  83. return $this->reload();
  84. break;
  85. case 'stop': // 停止运行
  86. return $this->stop();
  87. break;
  88. default:
  89. exit("{$op} command does not exist");
  90. break;
  91. }
  92. }
  93. /**
  94. * 启动
  95. */
  96. public function start()
  97. {
  98. date_default_timezone_set('PRC');
  99. // 构建Server对象,监听对应地址
  100. $this->serv = new \Swoole\Server($this->host, env('SWOOLE_PORT', $this->port));
  101. $this->serv->set($this->options);
  102. // 注册事件
  103. $this->serv->on('start', [$this, 'onStart']);
  104. $this->serv->on('receive', [$this, 'onReceive']);
  105. $this->serv->on('task', [$this, 'onTask']);
  106. $this->serv->on('finish', [$this, 'onFinish']);
  107. // Run worker
  108. echo "swoole start...\n";
  109. $this->serv->start();
  110. }
  111. // 安全重启
  112. public function reload()
  113. {
  114. $pids = file_exists($this->pidPath) ? file_get_contents($this->pidPath) : '';
  115. $pids = $pids ? explode("\n", $pids) : [];
  116. $masterPid = isset($pids[0]) ? $pids[0] : '';
  117. $managePid = isset($pids[1]) ? $pids[1] : '';
  118. if (empty($masterPid)) {
  119. return false;
  120. }
  121. if (!$this->status($masterPid)) {
  122. return false;
  123. }
  124. \Swoole\Process::kill($managePid, SIGUSR1);
  125. echo "swoole reload...\n";
  126. }
  127. /**
  128. * 停止
  129. * @param bool $smooth
  130. * @return bool
  131. */
  132. public function stop($smooth = false)
  133. {
  134. $pids = file_exists($this->pidPath) ? file_get_contents($this->pidPath) : '';
  135. $pids = $pids ? explode("\n", $pids) : [];
  136. $masterPid = isset($pids[0]) ? $pids[0] : '';
  137. if (empty($masterPid)) {
  138. return false;
  139. }
  140. if (!$this->status($masterPid)) {
  141. return false;
  142. }
  143. // 直接杀
  144. $stoSh = base_path().'/crontab/swooleTaskStop.sh';
  145. echo $stoSh;
  146. if(file_exists($stoSh) && function_exists('exec')){
  147. exec("{$stoSh}");
  148. }
  149. @unlink($this->pidPath);
  150. echo "swoole stop...\n";
  151. }
  152. /**
  153. * 状态
  154. * @return mixed
  155. */
  156. public function status($masterPid = 0)
  157. {
  158. $res = false;
  159. if (empty($masterPid) && file_exists($this->pidPath)) {
  160. $pids = file_get_contents($this->pidPath);
  161. $pids = $pids ? explode("\n", $pids) : [];
  162. $masterPid = isset($pids[0]) ? $pids[0] : '';
  163. }
  164. if ($masterPid) {
  165. $res = \Swoole\Process::kill($masterPid, 0);
  166. }
  167. return $res;
  168. }
  169. public function onStart($serv)
  170. {
  171. if (!is_dir(dirname($this->pidPath))) {
  172. @mkdir(dirname($this->pidPath), true, 755);
  173. }
  174. //记录进程id,脚本实现自动重启
  175. $pid = "{$serv->master_pid}\n{$serv->manager_pid}";
  176. file_put_contents($this->pidPath, $pid);
  177. // 定时任务
  178. $time = 0;
  179. $date = date('Y-m-d H:i:s');
  180. if(file_exists($this->options['log_file'])){
  181. $time = 0;
  182. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  183. }
  184. // 清除日志
  185. \swoole_timer_tick(1000, function ($timer) use ($serv, &$time) { // 启用定时器,每5秒执行一次
  186. $date = date('Y-m-d H:i:s');
  187. if($time>7200 && file_exists($this->options['log_file'])){
  188. $time = 0;
  189. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  190. }
  191. $time++;
  192. });
  193. // 充值订单状态检查
  194. \swoole_timer_tick(20000, function ($timer) use ($serv, &$time) { // 启用定时器,每20秒执行一次
  195. $date = date('Y-m-d H:i:s');
  196. $orders = PayOrdersService::make()->getCheckOrderList();
  197. if($orders){
  198. foreach ($orders as $k => $item){
  199. if(!RedisService::get('caches:task:lock:order_check_loaded_'.$k)){
  200. $taskData = [
  201. 'taskName' => 'checkOrder',
  202. 'name' => "充值订单状态更新",
  203. 'date' => date('Y-m-d'),
  204. 'params'=> $item,
  205. ];
  206. $res = $serv->task($taskData);
  207. RedisService::set('caches:task:lock:order_check_loaded_'.$k, true, rand(3,5));
  208. echo "[Task checkOrder {$date}] 充值订单状态更新结果:{$res}\n";
  209. }else{
  210. echo "[Task checkOrder {$date}] 充值订单状态更新间隔时间调用\n";
  211. }
  212. }
  213. }else{
  214. echo "[Task checkOrder {$date}] 暂无可验证状态的充值订单\n";
  215. }
  216. });
  217. // 充值订单支付成功下单失败退款
  218. \swoole_timer_tick(20000, function ($timer) use ($serv, &$time) { // 启用定时器,每20秒执行一次
  219. $date = date('Y-m-d H:i:s');
  220. $orders = PayOrdersService::make()->getFailedOrderList();
  221. if($orders){
  222. foreach ($orders as $k => $item){
  223. if(!RedisService::get('caches:task:lock:order_failed_loaded_'.$k)){
  224. $taskData = [
  225. 'taskName' => 'failedOrderRefund',
  226. 'name' => "充值订单下单失败退款",
  227. 'date' => date('Y-m-d'),
  228. 'params'=> $item,
  229. ];
  230. $res = $serv->task($taskData);
  231. RedisService::set('caches:task:lock:order_failed_loaded_'.$k, true, rand(3,5));
  232. echo "[Task failedOrderRefund {$date}] 充值订单下单失败退款结果:{$res}\n";
  233. }else{
  234. echo "[Task failedOrderRefund {$date}] 充值订单下单失败退款间隔时间调用\n";
  235. }
  236. }
  237. }else{
  238. echo "[Task failedOrderRefund {$date}] 暂无可退款的充值订单\n";
  239. }
  240. });
  241. // 订单自动收货
  242. \swoole_timer_tick(10000, function ($timer) use ($serv, &$time) { // 启用定时器,每10秒执行一次
  243. $date = date('Y-m-d H:i:s');
  244. $orders = OrderService::make()->getCompleteOrders();
  245. if($orders){
  246. foreach ($orders as $k => $item){
  247. $orderNo = isset($item['order_no'])?$item['order_no'] : '';
  248. if(!RedisService::get('caches:task:lock:order_complete_loaded_'.$orderNo)){
  249. $taskData = [
  250. 'taskName' => 'completeOrder',
  251. 'name' => "购物订单自动收货处理",
  252. 'date' => date('Y-m-d'),
  253. 'params'=> $item,
  254. ];
  255. $res = $serv->task($taskData);
  256. RedisService::set('caches:task:lock:order_complete_loaded_'.$k, true, rand(3,5));
  257. echo "[Task completeOrder {$date}] 购物订单【{$orderNo}】自动收货处理结果:{$res}\n";
  258. }else{
  259. echo "[Task completeOrder {$date}] 购物订单【{$orderNo}】自动收货处理间隔时间调用\n";
  260. }
  261. }
  262. }else{
  263. echo "[Task completeOrder {$date}] 暂无可自动收货的购物订单\n";
  264. }
  265. });
  266. }
  267. //监听连接进入事件
  268. public function onConnect($serv, $fd, $from_id)
  269. {
  270. $serv->send($fd, "Success {$fd}!");
  271. }
  272. // 监听数据接收事件
  273. public function onReceive(\Swoole\Server $serv, $fd, $from_id, $data)
  274. {
  275. echo "Get Message From Client {$fd}:{$data}\n";
  276. $res['result'] = 'success';
  277. $serv->send($fd, json_encode($res)); // 同步返回消息给客户端
  278. $serv->task($data); // 执行异步任务
  279. }
  280. /**
  281. * @param \Swoole\Server $serv
  282. * @param $task_id
  283. * @param $from_id
  284. * @param $data
  285. * @return false|string
  286. */
  287. public function onTask(\Swoole\Server $serv, $task_id, $from_id, $data)
  288. {
  289. $date = date('Y-m-d H:i:s');
  290. $taskName = isset($data['taskName']) ? $data['taskName'] : '';
  291. $params = isset($data['params']) ? $data['params'] : [];
  292. try {
  293. switch ($taskName) {
  294. case 'failedOrderRefund': // 支付成功下单失败退款
  295. // 调用处理
  296. if($res = PayOrdersService::make()->failedOrderRefund($params)){
  297. $res = is_array($res) && $res? json_encode($res, 256) : 'success';
  298. echo "[Task {$taskName} {$date}][{$task_id}] 充值订单下单失败退款处理结果:{$res}\n";
  299. }else{
  300. $error = PayOrdersService::make()->getError();
  301. $error = $error? lang($error) : 'failed';
  302. echo "[Task {$taskName} {$date}][{$task_id}] 充值订单下单失败退款处理结果:{$error}\n";
  303. }
  304. break;
  305. case 'checkOrder': // 更新状态
  306. // 调用处理
  307. if($res = PayOrdersService::make()->checkOrder($params)){
  308. $res = is_array($res) && $res? json_encode($res, 256) : 'success';
  309. echo "[Task {$taskName} {$date}][{$task_id}] 充值订单状态更新处理结果:{$res}\n";
  310. }else{
  311. $error = PayOrdersService::make()->getError();
  312. $error = $error? lang($error) : 'failed';
  313. echo "[Task {$taskName} {$date}][{$task_id}] 充值订单状态更新处理结果:{$error}\n";
  314. }
  315. break;
  316. case 'completeOrder': // 自动收货
  317. $orderId = isset($params['id'])? $params['id'] : 0;
  318. $orderNo = isset($params['order_no'])? $params['order_no'] : '';
  319. $userId = isset($params['user_id'])? $params['user_id'] : 0;
  320. if($orderId<=0 || $userId<=0){
  321. echo "[Task {$taskName} {$date}][{$task_id}] 该购物订单参数错误\n";
  322. return false;
  323. }
  324. // 调用处理
  325. if($res = OrderService::make()->complete($userId, $orderId, false)){
  326. $res = is_array($res) && $res? json_encode($res, 256) : 'success';
  327. echo "[Task {$taskName} {$date}][{$task_id}] 购物订单【{$orderNo}】自动收货处理结果:{$res}\n";
  328. }else{
  329. $error = OrderService::make()->getError();
  330. $error = $error? lang($error) : 'failed';
  331. echo "[Task {$taskName} {$date}][{$task_id}] 购物订单【{$orderNo}】自动收货处理结果:{$error}\n";
  332. }
  333. break;
  334. }
  335. } catch(\Exception $exception){
  336. return $exception->getMessage();
  337. }
  338. return "[{$task_id}]暂无任务处理";
  339. }
  340. /**
  341. * @param $serv swoole_server swoole_server对象
  342. * @param $task_id int 任务id
  343. * @param $data string 任务返回的数据
  344. */
  345. public function onFinish(\Swoole\Server $serv, $task_id, $data)
  346. {
  347. //
  348. //echo "任务处理完成...\n";
  349. }
  350. // 监听连接关闭事件
  351. public function onClose($serv, $fd, $from_id)
  352. {
  353. echo "Client {$fd} close connection\n";
  354. $serv->close();
  355. }
  356. }