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