find(); if (empty($token_info)) { throw new ServiceException('请先登录!'); } if ($token_info->expire <= time()) { throw new ServiceException('token已失效,请重新登录!'); } $this->user = $this->getUserInfo($token_info); } /** * 获取用户信息和好友列表 * @param $token_info UserToken token信息 * @return array|mixed|\PDOStatement|string|\think\Model|null */ protected function getUserInfo($token_info) { $info = Cache::get($token_info->token); if (!$info) { $info = User::where('id', $token_info->uid)->with(['userRelation' => function($query) { $query->where('status', UserRelation::STATUS_ACTIVE); }])->find(); Cache::set($token_info->token, $info); } return $info; } /** * 获取好友列表信息 * @param string $field string 要查询的字段 * @return array|mixed */ protected function getFriendList() { $list = Cache::get('user_friend_' . $this->user->id); if (!$list) { $user_relation = $this->user->userRelation; // 考虑到会出现缓存穿透的情况,如果返回为空也记录进缓存 if ($user_relation) { $friend = array_column($user_relation->toArray(), 'friend_id'); $list = User::whereIn('id', $friend)->select()->toArray(); } else { $list = $user_relation; } Cache::set('user_friend_' . $this->user->id, $list, 3600); } return $list; } }