SwooleAsyncTimer.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/4/9
  6. * Time: 下午5:15
  7. */
  8. namespace common\components;
  9. use anlity\swooleAsyncTimer\SocketInterface;
  10. use anlity\swooleAsyncTimer\SwooleAsyncTimerComponent;
  11. use backendApi\modules\v1\models\Admin;
  12. use common\components\Redis;
  13. use common\helpers\bonus\AutoClosePeriod;
  14. use common\helpers\Cache;
  15. use common\helpers\Date;
  16. use common\helpers\Tool;
  17. use common\libs\logging\system\ApiSystem;
  18. use common\libs\logging\system\AsyncSystem;
  19. use common\libs\taskQueue\Queue;
  20. use common\libs\taskQueue\TaskFunc;
  21. use common\models\UserInfo;
  22. use Yii;
  23. use anlity\swooleAsyncTimer\SwooleAsyncTimerController;
  24. use yii\base\Exception;
  25. use yii\helpers\Json;
  26. class SwooleAsyncTimer extends SwooleAsyncTimerComponent implements SocketInterface {
  27. const HANDLE_ADMIN_ASYNC = 'adminAsync';
  28. const HANDLE_ADMIN_PULL_MESSAGE = 'adminPullMsg';
  29. const HANDLE_USER_ASYNC = 'userAsync';
  30. const HANDLE_USER_PULL_MESSAGE = 'userPullMsg';
  31. const HANDLE_ADMIN_ASYNC_PERCENT = 'adminAsyncPercent';
  32. const COMMAND_PUSH_TO = 'pushTo';
  33. /**
  34. * 定时器自动执行任务
  35. * @param $timerId
  36. * @param $server
  37. * @return bool|void
  38. * @throws \yii\base\InvalidConfigException
  39. * @throws \yii\base\InvalidRouteException
  40. * @throws \yii\console\Exception
  41. * @throws \yii\db\Exception
  42. */
  43. public function timerCallback($timerId, $server){
  44. // 自动封期
  45. AutoClosePeriod::instance()->autoClose();
  46. // 自动发送订单
  47. TaskFunc::autoSendLogistics();
  48. // 自动执行任务队列中的任务
  49. Queue::instance()->consumeTask();
  50. return true;
  51. }
  52. /**
  53. * 初始化队列
  54. * @param $server
  55. * @param $workerId
  56. */
  57. public function onWorkerStart($server, $workerId){
  58. if($workerId == 1){
  59. // 重新更新自动封期的缓存
  60. AutoClosePeriod::instance()->setCloseTimeAndPeriodStat();
  61. // 初始化任务队列
  62. Queue::instance()->initRedis();
  63. // 初始化备份历史奖金数据表
  64. // TaskFunc::initAutoBakBalance();
  65. // 初始化发送订单物流信息表
  66. TaskFunc::initAutoOrderLogistics();
  67. echo '初始化swoole任务———— initAutoOrderLogistics' . PHP_EOL;
  68. }
  69. }
  70. public function onWorkerStop($server, $workerId){
  71. }
  72. public function onWorkerExit($server, $workerId){
  73. }
  74. public function onOpen($fd){
  75. }
  76. public function onClose($fd){
  77. }
  78. public function onMessage($fd, $data){
  79. // 如果传过来的是一个用户ID,则把$fd和userId绑定存入缓存
  80. $data = Json::decode($data);
  81. if(isset($data['userId']) && $data['userId'] != ''){
  82. Cache::setWebSocketFd($data['app'], $data['userId'], $fd);
  83. }
  84. }
  85. /**
  86. * 处理异步请求
  87. * @param $path
  88. * @param array $params
  89. * @param array $settings
  90. * @return bool
  91. * @throws \yii\base\Exception
  92. */
  93. public function asyncHandle($path, array $params = [], array $settings = []){
  94. // 把处理会员的UserId加进数组
  95. if(Yii::$app->user->id){
  96. $params['handleUserId'] = Yii::$app->user->id;
  97. if(Yii::$app->user->userInfo && isset(Yii::$app->user->userInfo['adminName'])){
  98. $params['handleUserName'] = Yii::$app->user->userInfo['adminName'];
  99. }
  100. } else {
  101. $params['handleUserId'] = null;
  102. $params['handleUserName'] = null;
  103. }
  104. $taskKey = Cache::setAsyncParams($params);
  105. $data = [
  106. 'data' => [
  107. [
  108. 'a' => $path,
  109. 'p' => [$taskKey],
  110. ]
  111. ],
  112. ];
  113. if($this->async(Json::encode($data), $settings)){
  114. return $taskKey;
  115. } else {
  116. return false;
  117. }
  118. }
  119. /**
  120. * 异步任务结束后给页面会员推送成功或者失败消息
  121. * @param $userId
  122. * @param string $message
  123. * @param bool $success
  124. * @param string $type message|progress
  125. */
  126. public function pushAsyncResultToAdmin($userId, $message='', $success = true, $type='message'){
  127. if($userId){
  128. $fd = Cache::getWebSocketFd(Cache::SOCKET_ADMIN, $userId);
  129. if($fd){
  130. try{
  131. $this->pushMsgByCli($fd, ['success'=>$success, 'handle'=>self::HANDLE_ADMIN_ASYNC, 'message'=>$message, 'type'=>$type]);
  132. } catch (\Exception $e){
  133. }
  134. }
  135. }
  136. }
  137. /**
  138. * 向管理员发送异步进度百分比
  139. * @param $percent
  140. * @param array $other
  141. */
  142. public function pushAsyncPercentToAdmin($percent, $other=[]){
  143. try{
  144. $this->pushMsgAllByCli(['handle'=>self::HANDLE_ADMIN_ASYNC_PERCENT, 'percent'=>$percent, 'other'=>$other]);
  145. } catch (\Exception $e){
  146. }
  147. }
  148. /**
  149. * 给前台会员发送webSocket消息
  150. * @param null $userId
  151. * @param string $message
  152. * @param bool $success
  153. * @return bool
  154. * @throws \Exception
  155. */
  156. public function pushMsgToUser($userId=null, $message='', $success = true){
  157. if($userId){
  158. $return = true;
  159. $fdAppFd = Cache::getWebSocketFd(Cache::SOCKET_USER_APP, $userId);
  160. if($fdAppFd && $return !== false){
  161. $return = $this->pushMsg($fdAppFd, ['success'=>$success, 'handle'=>self::HANDLE_USER_PULL_MESSAGE, 'message'=>$message]);
  162. }
  163. $fdPcFd = Cache::getWebSocketFd(Cache::SOCKET_USER_PC, $userId);
  164. if($fdPcFd && $return !== false){
  165. $return = $this->pushMsg($fdPcFd, ['success'=>$success, 'handle'=>self::HANDLE_USER_PULL_MESSAGE, 'message'=>$message]);
  166. }
  167. return $return;
  168. } else {
  169. return $this->pushMsgAll(['success'=>$success, 'handle'=>self::HANDLE_USER_PULL_MESSAGE, 'message'=>$message]);
  170. }
  171. }
  172. /**
  173. * 任务运行后
  174. * @param $server
  175. * @param $workerId
  176. * @param $action
  177. * @param $params
  178. */
  179. public function onTaskRunActionStart($server, $workerId, $action, $params){
  180. // 为了保证任务继续执行,此处将错误捕捉到不影响任务继续执行
  181. try {
  182. if(isset($params[0]) && $actionParams = Cache::getAsyncParamsWithoutDel($params[0])){
  183. // 记录日志
  184. if(strpos($action, 'log/') === false){
  185. $logApiSystem = new AsyncSystem();
  186. $logApiSystem->setRequestRoute($action)->setRequestContent($actionParams)->saveByConsole([
  187. 'apiName' => '异步'.$action,
  188. 'optUser' => isset($actionParams['handleUserName']) ? $actionParams['handleUserName'] : null,
  189. ]);
  190. }
  191. }
  192. } catch (\Exception $e) {
  193. // 忽略错误
  194. }
  195. }
  196. /**
  197. * 任务运行发生错误时
  198. * @param $fd
  199. * @param $data
  200. * @param $action
  201. * @param $params
  202. * @param $errorMessage
  203. */
  204. public function onTaskRunActionError($fd, $data, $action, $params, $errorMessage){
  205. // 为了保证任务继续执行,此处将错误捕捉到不影响任务继续执行
  206. try {
  207. // 记录日志
  208. $logApiSystem = new AsyncSystem();
  209. $logApiSystem->setRequestRoute($action)->setResponseContent(['errorMessage' => $errorMessage])->saveByConsole([
  210. 'apiName' => '异步错误'.$action,
  211. ]);
  212. } catch (\Exception $e) {
  213. // 忽略错误
  214. }
  215. }
  216. }