@stkevintan
2015-05-15T17:42:04.000000Z
字数 2560
阅读 750
因为匿名代理服务器为了混淆用户的真是地理信息,往往会产生很多没有实际作用虚假信息。因此,代理服务器需要接收和发出的http IO会比一般情况的要多。而Node.js正好有着出色的异步IO性能。非常适合本项目。
router.post('/', function (req, res, next) {
psEncrypt(req.body, function (err, sres) {
...
res.send(result);
}
2.匿名器查询历史数据库
var searchHis = function (psmodel, callback) {
psDB.findOne(psmodel.toEntity({
result: {$exists: true}
}), function (err, doc) {
callback(err, psmodel, doc);
});
}
3.如果没有相同的历史记录,则将该数据存入数据库,等待分解重构算法处理。
var storeRec = function (psmodel, doc, callback) {
if (doc) {
debug.log('not through storeRec');
callback(null, doc);
} else if (psmodel.mark.on) {
psDB.findOne(psmodel.toEntity({
result: {$exists: false}
}),function(err,doc){
err && callback(err);
if(doc)delaycb(null,doc);
else{
psDB.create(psmodel.toEntity(),delaycb);
}
});
} else {
debug.log('Not to Encrypt,Get Data from Server');
psmodel.handle(psDB, function (err, res) {
callback(err, {result: res});
});
}
function delaycb(err,doc){
setTimeout(function () {
callback(err, doc);
}, config.ResponseTimeOut);
}
}
4.经过ResponseTimeOut的时间之后,查看该条数据是否被处理,否则,直接发出请求
var doWork = function (doc, callback) {
if (doc && doc.result) {
debug.log('Not Via doWork');
callback(null, doc.result);
} else psDB.findById(doc._id, {
_id: 0,
timestamp: 0,
__v: 0
}, function (err, _doc) {
//debug.log(_doc.toJSON());
if (err) callback(err);
else if (_doc.result) {
debug.log('Not via Superagent');
callback(null, _doc.result);
} else {
//Get Data from Server
debug.log('_doc',_doc);
new psModel(_doc).handle(callback);
}
});
}
5.分解重构算法
1)设定一个数据库守护进程,每隔特定时间处理数据库中未被处理的请求。
setInterval(function () {
//debug.log('start to check database');
tot=db.search({result:{$exists:false}});
if(tot>k){
//refactor and group
...
}
}, config.DaemonInterval);
2)将得到请求数组重构,通过dfs将参数分解。
colArray=[arg1,arg2,arg3,arg4];
async.eachLimit(tasks, limit, function (item, callback) {
item.forEach(function (item) {
colArray.forEach(function ($) {
ref[$].push(item[$]);
});
});
// unique Array
colArray.forEach(function ($) {
ref[$] = utils.unique(ref[$]);
});
//refactor
dfs(0, {});
}, function (err) {
err && debug.log('refactor error!', err);
});
3)将分解后的数组按照K等级进行重组
var group = function (k, total, contain) {
var c = total / k;
var r = total % k;
if (c < r) return;
//r:(k+1) c-r:k
var ret = [];
var index = 0;
var alloc = [{unit: r, num: k + 1}, {unit: c - r, num: k}];
alloc.forEach(function ($) {
for (var i = 0; i < $.unit; i++) {
var buk = [];
for (var j = 0; j < $.num; j++) {
buk.push(contain[index++]);
}
ret.push(buk);
}
});
return ret;
}
4.将重组后的新的请求数组使用异步并行的方式向百度地图服务器发出请求,得到结果:
superagent.get(serviceUrl)
.query(querys)
.end(function (err, res) {
callback(err, res.text);
//update database
if (db) {
db.update(
entitys,//update criteria
{$set: {result: res.text}},//update action
{upsert: true, multi: true},//update option
function (err) {
err && debug.log('database update error!');
});
}
});