get('redis'); $this->redis = new \Redis(); try { $this->redis->connect($config['host'], $config['port']); } catch (\Exception $e) { throw new \Exception(mb_convert_encoding($e->getMessage(), 'utf8', 'gbk')); } if ($config['auth']) { $this->redis->auth($config['auth']); } } /** * 设置缓存 * @param string $key * @param string $value * @param int $timeout * @return bool */ public function set($key, $value, $timeout = 10) { if (is_array($value) || is_object($value)) { $value = json_encode($value); } $timeout = $timeout == 0 ? null : $timeout; return $this->redis->set($key, $value, $timeout); } /** * 获取缓存的值 * @param null $key * @param null $callable * @return bool|mixed|string */ public function get($key = null, $callable = null) { $value = $this->redis->get($key); // 如果获取不到结果但是callable存在 if ($value === false && is_callable($callable)) { return $callable($this); } // 判断值是否是json字符串 $jsonDecode = json_decode($value, true); if (is_null($jsonDecode)) { // 原始数据 return $value; } // 返回转换后的数据 return $jsonDecode; } /** * 删除缓存 * @param string $key * @return int */ public function remove($key = null) { return $this->redis->del($key); } /** * 判断缓存是否设置 * @param $key * @return bool */ public function exists($key) { return $this->redis->exists($key); } }