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\bonus\Calc\CalcConsole;
  15. use common\helpers\Cache;
  16. use common\helpers\Date;
  17. use common\helpers\Tool;
  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. // 自动执行任务队列中的任务
  48. Queue::instance()->consumeTask();
  49. // 实时监听计算系统修改的period表字段
  50. CalcConsole::listenCalcPeriod();
  51. return true;
  52. }
  53. /**
  54. * 初始化队列
  55. * @param $server
  56. * @param $workerId
  57. */
  58. public function onWorkerStart($server, $workerId){
  59. if($workerId == 1){
  60. // 重新更新自动封期的缓存
  61. AutoClosePeriod::instance()->setCloseTimeAndPeriodStat();
  62. // 初始化任务队列
  63. Queue::instance()->initRedis();
  64. // 初始化备份历史奖金数据表
  65. // TaskFunc::initAutoBakBalance();
  66. }
  67. }
  68. public function onWorkerStop($server, $workerId){
  69. }
  70. public function onWorkerExit($server, $workerId){
  71. }
  72. public function onOpen($fd){
  73. }
  74. public function onClose($fd){
  75. }
  76. public function onMessage($fd, $data){
  77. // 如果传过来的是一个用户ID,则把$fd和userId绑定存入缓存
  78. $data = Json::decode($data);
  79. if(isset($data['userId']) && $data['userId'] != ''){
  80. Cache::setWebSocketFd($data['app'], $data['userId'], $fd);
  81. }
  82. }
  83. /**
  84. * 处理异步请求
  85. * @param $path
  86. * @param array $params
  87. * @param array $settings
  88. * @return bool
  89. * @throws \yii\base\Exception
  90. */
  91. public function asyncHandle($path, array $params = [], array $settings = []){
  92. // 把处理会员的UserId加进数组
  93. if(Yii::$app->user->id){
  94. $params['handleUserId'] = Yii::$app->user->id;
  95. if(Yii::$app->user->userInfo && isset(Yii::$app->user->userInfo['adminName'])){
  96. $params['handleUserName'] = Yii::$app->user->userInfo['adminName'];
  97. }
  98. } else {
  99. $params['handleUserId'] = null;
  100. $params['handleUserName'] = null;
  101. }
  102. $taskKey = Cache::setAsyncParams($params);
  103. $data = [
  104. 'data' => [
  105. [
  106. 'a' => $path,
  107. 'p' => [$taskKey],
  108. ]
  109. ],
  110. ];
  111. if($this->async(Json::encode($data), $settings)){
  112. return $taskKey;
  113. } else {
  114. return false;
  115. }
  116. }
  117. /**
  118. * 异步任务结束后给页面会员推送成功或者失败消息
  119. * @param $userId
  120. * @param string $message
  121. * @param bool $success
  122. * @param string $type message|progress
  123. */
  124. public function pushAsyncResultToAdmin($userId, $message='', $success = true, $type='message'){
  125. if($userId){
  126. $fd = Cache::getWebSocketFd(Cache::SOCKET_ADMIN, $userId);
  127. if($fd){
  128. try{
  129. $this->pushMsgByCli($fd, ['success'=>$success, 'handle'=>self::HANDLE_ADMIN_ASYNC, 'message'=>$message, 'type'=>$type]);
  130. } catch (\Exception $e){
  131. }
  132. }
  133. }
  134. }
  135. /**
  136. * 向管理员发送异步进度百分比
  137. * @param $percent
  138. * @param array $other
  139. */
  140. public function pushAsyncPercentToAdmin($percent, $other=[]){
  141. try{
  142. $this->pushMsgAllByCli(['handle'=>self::HANDLE_ADMIN_ASYNC_PERCENT, 'percent'=>$percent, 'other'=>$other]);
  143. } catch (\Exception $e){
  144. }
  145. }
  146. /**
  147. * 给前台会员发送webSocket消息
  148. * @param null $userId
  149. * @param string $message
  150. * @param bool $success
  151. * @return bool
  152. * @throws \Exception
  153. */
  154. public function pushMsgToUser($userId=null, $message='', $success = true){
  155. if($userId){
  156. $return = true;
  157. $fdAppFd = Cache::getWebSocketFd(Cache::SOCKET_USER_APP, $userId);
  158. if($fdAppFd && $return !== false){
  159. $return = $this->pushMsg($fdAppFd, ['success'=>$success, 'handle'=>self::HANDLE_USER_PULL_MESSAGE, 'message'=>$message]);
  160. }
  161. $fdPcFd = Cache::getWebSocketFd(Cache::SOCKET_USER_PC, $userId);
  162. if($fdPcFd && $return !== false){
  163. $return = $this->pushMsg($fdPcFd, ['success'=>$success, 'handle'=>self::HANDLE_USER_PULL_MESSAGE, 'message'=>$message]);
  164. }
  165. return $return;
  166. } else {
  167. return $this->pushMsgAll(['success'=>$success, 'handle'=>self::HANDLE_USER_PULL_MESSAGE, 'message'=>$message]);
  168. }
  169. }
  170. /**
  171. * 任务运行后
  172. * @param $server
  173. * @param $workerId
  174. * @param $action
  175. * @param $params
  176. */
  177. public function onTaskRunActionStart($server, $workerId, $action, $params){
  178. // 为了保证任务继续执行,此处将错误捕捉到不影响任务继续执行
  179. try {
  180. if(isset($params[0]) && $actionParams = Cache::getAsyncParamsWithoutDel($params[0])){
  181. // 记录日志
  182. if(strpos($action, 'log/') === false){
  183. $logApiSystem = new AsyncSystem();
  184. $logApiSystem->setRequestRoute($action)->setRequestContent($actionParams)->saveByConsole([
  185. 'apiName' => '异步'.$action,
  186. 'optUser' => isset($actionParams['handleUserName']) ? $actionParams['handleUserName'] : null,
  187. ]);
  188. }
  189. }
  190. } catch (\Exception $e) {
  191. // 忽略错误
  192. }
  193. }
  194. /**
  195. * 任务运行发生错误时
  196. * @param $fd
  197. * @param $data
  198. * @param $action
  199. * @param $params
  200. * @param $errorMessage
  201. */
  202. public function onTaskRunActionError($fd, $data, $action, $params, $errorMessage){
  203. // 为了保证任务继续执行,此处将错误捕捉到不影响任务继续执行
  204. try {
  205. // 记录日志
  206. $logApiSystem = new AsyncSystem();
  207. $logApiSystem->setRequestRoute($action)->setResponseContent(['errorMessage' => $errorMessage])->saveByConsole([
  208. 'apiName' => '异步错误'.$action,
  209. ]);
  210. } catch (\Exception $e) {
  211. // 忽略错误
  212. }
  213. }
  214. }