SwooleTask.php 12 KB

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