游戏服务器mysql封装_游戏服务器-数据库封装

一、什么是单例模式

单例模式就是一个类有且只有一个对象。在第一次使用这个类时,生成一个对象并常驻内存,在后续的使用中都会直接返回改对象而无需额外生成新的对象,在本次会话结束后由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); //我的等级排名

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值