关于利用事件队列解决雪崩问题?
场景: 获取微信的token的过程有点慢,而且token是有有效期的,所以当并发过来请求时,实际上只需要一个请求微信服务器,然后把结果共享就可以了。
想起node中深入浅出有关于利用事件队列解决雪崩的问题,那怎么用到这里呢? 能用到这里吗? 如果不能有什么好的办法呢?
//并发从这里开始
var proxy = new EventProxy();
var status = "ready";
var select = function (callback) {
proxy.once("selected", callback);
if (status === "ready") {
status = "pending";
db.select("SQL", function (results) {
proxy.emit("selected", results);
status = "ready";
});
}
};
但是在express中的controller怎么用呢?
var proxy = new EventProxy();
var status = "ready";
//并发体现在这里
router.all('index', function(req, res) {
/*
微信的耗时请求
var select = function (callback) {
proxy.once("selected", callback);
if (status === "ready") {
status = "pending";
db.select("SQL", function (results) {
proxy.emit("selected", results);
status = "ready";
});
}
};
*/
});
10 回复
@i5ting 这样改可以吧
var proxy = new EventProxy();
var status = "ready";
//并发体现在这里
router.all('index', function(req, res) {
/*
微信的耗时请求
var select = function (callback) {
proxy.once("selected", callback);
if (status === "ready") {
status = "pending";
db.select("SQL", function (results) {
proxy.emit("selected", results);
status = "ready";
});
}
};
*/
});
EventProxy 不够直观,用 Promise 大法
class TokenService {
getToken() {
if (this.requesting === undefined) {
var self = this;
this.requesting = db.query('SELECT token FROM users WHERE id=...').finally(function() {
delete self.requesting;
})
}
return this.requesting;
}
}