本文demo给予 上一片博文(pomelo链接mysql)
暴露给客户端的servers 逻辑部分解耦到service服务,达到解耦的目的
需求:吧购买物品解耦到service目录
添加持久对象: this.GoodsService
module.exports = function (app) {
return new Handler(app);
};
var Handler = function (app) {
this.app = app;
var GoodsService = require(app.getBase() + "/app/service/game/GoodsService.js");
this.GoodsService = new GoodsService();
};
var handler = Handler.prototype;
修改gameHandler.js里的 buyGoods函数的代码
handler.buyGoods = function (msg, session, next) {
var id = msg.id;
var count = msg.count;
///////////////////////////////
if (id == "100" && count == 1) {//验证购买条件 //允许购买
this.GoodsService.buyGoods(msg.id, session.uid, function (err, res) {
if (err) { // 购买失败
console.error("[Error]:数据库服务器错误");
next(null, { msg: "购买失败,服务器错误!", code: 200 });
}
else {//购买成功
next(null, { msg: "购买物品:#活血丹 成功", code: 200 });
}
});
} else { // 不允许购买
next(null, { msg: "你的金币不足,购买失败", code: 200 });
}
}
//还可以进一步解耦为
handler.buyGoods = function (msg, session, next) {
this.GoodsService.buyGoods(msg.id, session.uid, next);
}
添加 game-server\app\service\game\GoodsService.js
function GoodsService() {
console.error("[GoodsService]:new GoodsService"); // 检测不同的客户端是否会new 该脚本
}
GoodsService.prototype.buyGoods = function (id, owner, cb) {
var sql = " insert into `goods` (`id`, `owner`) VALUES(?, ?)";
var args = [id, owner];
var dbclient = pomelo.app.get('dbclient');//获取全局mysql client
console.log(dbclient);
dbclient.query(sql, args, function (err, res) {//执行sql语句 函数insert和query等效
cb(err, res);
});
};
module.exports = GoodsService;
//进一步解耦 在这里 不列出
新建多个客户端连接,构造器只被调用了一次说明了所有客户端 都是用的同一个 服务器的 实例化的handler ,所以用路由来分配服务器压力格外重要