'127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'timeout' => 0, 'persistent' => false, ]; /** * 构造函数 * @throws \BadFunctionCallException * @access public */ public function __construct() { if (!extension_loaded('redis')) { throw new \BadFunctionCallException('not support: redis'); } $this->options = array_merge($this->options, \think\Config::get('redis')); // 读取redis的配置信息 $this->handler = new \Redis; if ($this->options['persistent']) { $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']); } else { $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']); } if ('' != $this->options['password']) { $this->handler->auth($this->options['password']); } if (0 != $this->options['select']) { $this->handler->select($this->options['select']); } } /** * 存储Token * @param int $userID 用户ID * @param string $token 凭证 * @return bool */ public function set(int $userID, string $token): bool { return $this->handler->hSet($this->userTokenKey, $userID, $token); } /** * 获取Token内的信息 * @param string $token * @return array */ public function get(int $userID): array { // 判断redis中是否存在 $value = $this->handler->hGet($this->userTokenKey, $userID); if (is_null($value) || false === $value) { return []; } // 解码 $tokenArr = json_decode($value,true); if (is_null($tokenArr) || false === $tokenArr) { return []; } return $tokenArr; } /** * 获取加密后的Token * @param int $userID 用户ID * @return string */ public function getEncryptedToken(int $userID): string { // 对json数据进行base64编码 return base64_encode(json_encode(self::get($userID), JSON_UNESCAPED_UNICODE)); } /** * 判断Token是否可用 * @param string $token Token * @param int $userID 会员ID * @return boolean */ public function check(int $userID, string $token): bool { $data = self::get($userID); return $data && $data['user_id'] == $userID && $data['token'] == $token && $data['create_time'] + Config::get('token.duration') > time(); } /** * 删除用户的Token * @param int $userID 会员ID * @return boolean */ public function delete(int $userID): bool { $data = $this->get($userID); if ($data) { $this->handler->hDel($this->userTokenKey, $userID); } return true; } }