<?php/** * created by phpstorm. * user: administrator * date: 2018/7/16 * time: 14:19 *//** * 实现同步实现同步redis */namespace app\common\lib\redis;class predis{ /** * 单例模式的变量 * @var null */ private static $_instance=null; public $redis = ''; /** * 单例模式应用防止多次连接redis,提高性能 * @return predis|null */ public static function getinstance(){ if(is_null(self::$_instance) || empty(self::$_instance)){ self::$_instance = new self(); } return self::$_instance; } /** *连接redis */ private function __construct() { $this->redis = new \redis(); $result = $this->redis->connect(config('redis.host'), config('redis.port')); if($result==false){ throw new \exception('redis connect fail'); } } /** *redis set方法的应用 * @param $key * @param $value * @param int $time * @return bool|string */ public function set($key,$value,$time=0){ if(!$key){ return ''; } if(is_array($value)){ $value = json_encode($value); } if(!$time){ return $this->redis->set($key,$value); } return $this->redis->setex($key,$time,$value); } /** * redis get方法 * @param $key * @return string */ public function get($key){ if(!$key){ return ''; } return $this->redis->get($key); } /** * 获取有序列表的结合 * @param $key * @return array */ public function smembers($key) { return $this->redis->smembers($key); } /** * 获取list的元素值结合 */ public function lrange($key){ var_dump($key); return $this->redis->lrange($key,0,-1); } /** * 魔术方法__call */ public function __call($name, $arguments) { echo $name.php_eol; print_r($arguments); if(count($arguments) != 2) { return ''; } $this->redis->$name($arguments[0], $arguments[1]); } }
以上就是在 php 中将 redis 封装成单例模式的详细内容。
