SwooleAsyncTimer.php 7.7 KB

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