节点并发/快速请求生命周期/可能的竞争状态?

我正在构build一个多租户Node应用程序,租户通过查询string进行标识。

我也有一个API客户端,基于该网站进行身份validation(oauth)请求。

我的问题是,我是否可以保持API客户端作为一个单身的对象,只是更新其中的会话 – 是否会遇到竞争条件,因为另一个请求进来,同时我进行asynchronous与客户的操作。

const session = new Session({ apiKey: 'xxx', secret: 'xxx' }) const client = new Client({ session }) app.use((req, res, next)=> { res.locals.client = client; next() }) app.use((req, res, next)=> { let { client, db } = res.locals; if (req.query.tenant) { return db.Tenant.findOne({ tenant: req.query.tenant }) .then((tenant)=> { client.updateSession({ access_token: tenant ? tenant.access_token : null }) next() }) } next(); }) app.get('/test/api', (req, res)=> { let { client } = res.locals; client.get('products').then((products)=> { // What if another request from another tenant comes in right here? // Is it possible for the session to be swapped out underneath me? return products.get(2).someAsyncFunc().then((product)=> { return res.json(product) }) }) }) 

我的问题是,我是否可以保持API客户端作为一个单身的对象,只是更新里面的会话

不,请为每个请求创build一个唯一的Client对象实例。 肯定client.updateSession看起来像一个共享对象与非共享数据。

只要改变这一行

 res.locals.client = client; 

对此:

 res.locals.client = new Client(new Session({apiKey: 'x', secret: 'x'})); 

你现在应该安全了。