SwooleAsyncTimer.php 7.5 KB

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