关于利用事件队列解决雪崩问题?
发布于 8 年前 作者 suntopo 4465 次浏览 来自 问答

场景: 获取微信的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 回复

是不是把 微信的耗时操作独立出来,然后按照原来解决雪崩的方法写,然后引到controller中,就可以了? 从而使得并发转移到独立出来的方法上面了

token怎么存你就都没搞清楚吧?

@i5ting 怎么存?怎么说呢? 其实没搞明白的是这里proxy.once(“selected”, callback)和里面的消息队列

@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;
	}
}

@klesh 没怎么用过promise, 您这里是怎么控制雪崩的呢?

这个,网上有很多讲promise的,搜下。 这里就是靠 requesting 这个 promise 变量,在requesting执行未完成前重复调用 getToken 将会得到同一个 promise 对象,那就不存在雪崩问题了。

同样关注此问题!

多个请求共用一个promise。

回到顶部