SwooleTask.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\Api\BonusService;
  4. use App\Services\RedisService;
  5. use Illuminate\Console\Command;
  6. use App\Services\Hapi\IssueService;
  7. use App\Services\Hapi\LotteryService;
  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 = 6621;
  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' => 0, //日志级别 范围是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, $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. $managePid = isset($pids[1]) ? $pids[1] : '';
  139. if (empty($masterPid)) {
  140. return false;
  141. }
  142. if (!$this->status($masterPid)) {
  143. return false;
  144. }
  145. if ($smooth) {
  146. \Swoole\Process::kill($masterPid, SIGTERM);
  147. try {
  148. while (true) {
  149. \Swoole\Process::kill($masterPid, 0);
  150. }
  151. } catch (\Exception $exception) {
  152. }
  153. } else {
  154. \Swoole\Process::kill($masterPid, SIGKILL);
  155. }
  156. if($managePid){
  157. \Swoole\Process::kill($managePid, SIGKILL);
  158. }
  159. @unlink($this->pidPath);
  160. echo "swoole stop...\n";
  161. }
  162. /**
  163. * 状态
  164. * @return mixed
  165. */
  166. public function status($masterPid = 0)
  167. {
  168. $res = false;
  169. if (empty($masterPid) && file_exists($this->pidPath)) {
  170. $pids = file_get_contents($this->pidPath);
  171. $pids = $pids ? explode("\n", $pids) : [];
  172. $masterPid = isset($pids[0]) ? $pids[0] : '';
  173. }
  174. if ($masterPid) {
  175. $res = \Swoole\Process::kill($masterPid, 0);
  176. }
  177. return $res;
  178. }
  179. public function onStart($serv)
  180. {
  181. if (!is_dir(dirname($this->pidPath))) {
  182. @mkdir(dirname($this->pidPath), true, 755);
  183. }
  184. //记录进程id,脚本实现自动重启
  185. $pid = "{$serv->master_pid}\n{$serv->manager_pid}";
  186. file_put_contents($this->pidPath, $pid);
  187. // 定时任务
  188. $time = 0;
  189. $date = date('Y-m-d H:i:s');
  190. if(file_exists($this->options['log_file'])){
  191. $time = 0;
  192. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  193. }
  194. \swoole_timer_tick(120000, function ($timer) use ($serv, &$time) { // 启用定时器,每120秒执行一次
  195. // \Swoole\Timer::tick(2000, function ($timer) use ($serv, &$time) { // 启用定时器,每120秒执行一次
  196. $date = date('Y-m-d H:i:s');
  197. if($time>3600 && file_exists($this->options['log_file'])){
  198. $time = 0;
  199. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  200. }
  201. $time++;
  202. if(!RedisService::get('caches:task:lock:loaded')){
  203. $taskData = [
  204. 'taskName' => 'OrderSettle',
  205. 'name' => "订单佣金结算任务",
  206. 'date' => date('Y-m-d'),
  207. ];
  208. $res = $serv->task($taskData);
  209. RedisService::set('caches:task:lock:loaded', true, rand(3,5));
  210. echo "[Task OrderSettle {$date}] 订单结算任务调用完成:{$res}\n";
  211. }else{
  212. echo "[Task OrderSettle {$date}] 间隔时间调用\n";
  213. }
  214. });
  215. }
  216. //监听连接进入事件
  217. public function onConnect($serv, $fd, $from_id)
  218. {
  219. $serv->send($fd, "Success {$fd}!");
  220. }
  221. // 监听数据接收事件
  222. public function onReceive(\Swoole\Server $serv, $fd, $from_id, $data)
  223. {
  224. echo "Get Message From Client {$fd}:{$data}\n";
  225. $res['result'] = 'success';
  226. $serv->send($fd, json_encode($res)); // 同步返回消息给客户端
  227. $serv->task($data); // 执行异步任务
  228. }
  229. /**
  230. * @param \Swoole\Server $serv
  231. * @param $task_id
  232. * @param $from_id
  233. * @param $data
  234. * @return false|string
  235. */
  236. public function onTask(\Swoole\Server $serv, $task_id, $from_id, $data)
  237. {
  238. $date = date('Y-m-d H:i:s');
  239. $taskName = isset($data['taskName']) ? $data['taskName'] : '';
  240. switch ($taskName) {
  241. case 'OrderSettle': // 订单结算
  242. // 时间限制
  243. if(date('H:i') >= env('SETTLE_TIME','06:00')){
  244. echo "[Task {$taskName} {$date}] 不在运行时间段内\n";
  245. return false;
  246. }
  247. // 调用处理
  248. if($res = BonusService::make()->orderSettle()){
  249. $res = is_array($res) && $res? json_encode($res, 256) : 'success';
  250. echo "[Task {$taskName} {$date}] 订单结算结果:{$res}\n";
  251. }else{
  252. $error = BonusService::make()->getError();
  253. $error = $error? lang($error) : 'failed';
  254. echo "[Task {$taskName} {$date}] 订单结算结果:{$error}\n";
  255. }
  256. break;
  257. }
  258. return '暂无任务处理';
  259. }
  260. /**
  261. * @param $serv swoole_server swoole_server对象
  262. * @param $task_id int 任务id
  263. * @param $data string 任务返回的数据
  264. */
  265. public function onFinish(\Swoole\Server $serv, $task_id, $data)
  266. {
  267. //
  268. echo "任务处理完成...\n";
  269. }
  270. // 监听连接关闭事件
  271. public function onClose($serv, $fd, $from_id)
  272. {
  273. echo "Client {$fd} close connection\n";
  274. $serv->close();
  275. }
  276. }