简单的redis单例类
2018-09-16 本文已影响0人
蓝天_337b
/*
自己写着玩
*/
<?php
class redis
{
const REDISHOST = '127.0.0.1';
const REDISPORT = '6379';
const REDISPASWORD = '';
const REDISDBNAME = 0;
private static $_obj = null;
private function __construct(){
}
private function __clone(){}//禁止克隆
private static function connect_redis($dbname = null)
{
try{
self::$_obj = new redis();
self::$_obj->connect(self::REDISHOST,self::REDISPORT);
if(self::REDISPASWORD){
self::$_obj->auth(self::REDISPASWORD);
}
if($dbname){
$dbname = (int)$dbname;
self::$_obj->select($dbname);
}else{
self::$_obj->select(self::REDISDBNAME);
}
}catch (Exception $e){
exit($e->getMessage().'<br/>');
}
return self::$_obj;
}
public static function getRedis()
{
if(!self::$_obj){
self::$_obj = self::connect_redis();
}
return self::$_obj;
}
public function set($key,$value)
{
if(!empty($key) && !empty($value)){
return self::$_obj->set($key,$value);
}else{
return false;
}
}
public function get($key)
{
if(!empty($key)){
return self::$_obj->get($key);
}else{
return false;
}
}
public function exists($key)
{
if(!empty($key)){
return self::$_obj->exists($key);
}else{
return false;
}
}
}
//直接调用getredis
$redis = redis::getredis();
$redis->get('a');