SwooleAsyncTimer.php 7.4 KB

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