type = $type; // 只有在Swoole扩展已加载且swoole.server服务存在时才获取server实例 if (extension_loaded('swoole') && app()->has('swoole.server')) { $this->server = app('swoole.server'); } else { $this->server = null; } } /** * @param array $data * @return $this * @author xaboy * @day 2020-04-15 */ public function setData(array $data) { $this->data = $data; return $this; } /** * @param int $workId * @return mixed * @author xaboy * @day 2020-04-15 */ public function push(int $workId = -1) { try { // 只有在有Swoole服务器实例时才发送任务 if ($this->server instanceof \Swoole\Server) { return $this->server->task(['type' => $this->type, 'data' => $this->data], $workId); } else { // 非Swoole环境下记录日志但不抛出异常 Log::info('Swoole服务器不可用,任务未发送: ' . $this->type); return false; } } catch (\Exception $e) { Log::info('发送 Task 失败' . $e->getMessage()); } } /** * @param string $type * @return static * @author xaboy * @day 2020/5/25 */ public static function create(string $type) { return new static($type); } public static function user($uid, $data) { $type = 'user'; return self::create('message')->setData(compact('type', 'uid', 'data'))->push(); } public static function admin(string $msgType, array $msgData, $uid = []) { return self::create('admin')->setData([ 'uid' => $uid, 'data' => [ 'type' => $msgType, 'data' => $msgData ] ])->push(); } public static function merchant(string $msgType, array $msgData, int $merId, $uid = []) { return self::create('merchant')->setData([ 'uid' => $uid, 'mer_id' => $merId, 'data' => [ 'type' => $msgType, 'data' => $msgData ] ])->push(); } /** * @param $merId * @param array $result * @return mixed * @author xaboy * @day 2020/5/25 */ public static function log($merId, array $result) { return self::create('log')->setData(compact('merId', 'result'))->push(); } /** * @param int $uid * @param int $type_id * @param string $type * @param string $content * @return mixed * @author xaboy * @day 2020/6/25 */ public static function visit(int $uid, int $type_id, string $type, string $content = '') { return self::create('visit')->setData(compact('uid', 'type', 'type_id', 'content'))->push(); } public static function __callStatic($name, $arguments) { return self::create($name)->setData($arguments[0])->push(); } }