SwooleAsyncTimer.php 7.7 KB

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