一、什么是单例模式
单例模式就是一个类有且只有一个对象。在第一次使用这个类时,生成一个对象并常驻内存,在后续的使用中都会直接返回改对象而无需额外生成新的对象,在本次会话结束后由php自动回收。这样可以大大减少服务器开销。
二、封装实例
/**
* 单例Redis操作类
* User: LeeKay
* Date: 2015/12/1
* Time: 18:20
*/
class MyRedis extends Redis{
protected static $_user_db = null; //玩家数据库编号
// redis实例
protected static $_user_redis = null; //玩家
protected static $_common_redis = null; //逻辑/公共
protected static $_global_redis = null; //全服
protected static $_log_redis = null; //日志
/**
* 角色数据库对象
*
* @param $puid
*
* @return MyRedis
*/
public function getUserRedis($puid){
global $cfg;
$db = database($puid);
if($db == self::$_user_db AND null !== self::$_user_redis){
return self::$_user_redis;
}else{
$redis_cfg = $cfg['db_User_Redis_' . $db];
self::$_user_redis = new self();
$host = $redis_cfg['host'];
$port = $redis_cfg['port'];
self::$_user_redis->connect($host, $port);
self::$_user_db = $db;
return self::$_user_redis;
}
}
/**
* 服务器公共数据库对象
* @return MyRedis
*/
public function getCommonRedis(){
global $cfg;
if(null === self::$_common_redis){
$redis_cfg = $cfg['db_Common_Redis'];
self::$_common_redis = new self();
$host = $redis_cfg['host'];
$port = $redis_cfg['port'];
self::$_common_redis->connect($host, $port);
}
return self::$_common_redis;
}
/**
* 全服通用数据库对象
* @return MyRedis
*/
public function getGlobalRedis(){
global $cfg;
if(null === self::$_global_redis){
$redis_cfg = $cfg['db_Global_Redis'];
self::$_global_redis = new self();
$host = $redis_cfg['host'];
$port = $redis_cfg['port'];
self::$_global_redis->connect($host, $port);
}
return self::$_global_redis;
}
/**
* 服务器日志队列数据库对象
* @return MyRedis
*/
public function getLogRedis(){
global $cfg;
if(null === self::$_log_redis){
$redis_cfg = $cfg['db_Log_Redis'];
self::$_log_redis = new self();
$host = $redis_cfg['host'];
$port = $redis_cfg['port'];
self::$_log_redis->connect($host, $port);
}
return self::$_log_redis;
}
}
三、应用实例
$uid = 1;//用户ID
$my_redis = new MyRedis();
$role_info = $my_redis->getUserRedis($puid)->GET(Redis_Pfx_RoleInfo . $puid); //角色信息
$level_rank = $my_redis->getLogicRedis()->ZREVRANK(Redis_Pfx_LevelRank, $puid); //我的等级排名