我有以下koa服务器
didExitRegion
我同时从两个客户端点击const koa = require('koa');
const router = require('koa-router')();
// Intialize the base application
const app = koa();
// Define the logger function
app.use(function *(next) {
console.log('Start processing');
// before (Downstream)
var timestampBefore = new Date().getTime();
yield next;
// After (Upstream)
var timestampAfter = new Date().getTime();
var difference = timestampAfter - timestampBefore;
console.log("Processing took " + difference + "ms");
});
// Intialize router
app
.use(router.routes())
.use(router.allowedMethods());
router.get('/users', function *() {
yield new Promise((resolve, reject) => {
setTimeout(() => resolve(this.body = ['User 1', 'User 2']), 3000);
});
});
app.listen(3000, () => console.log('Server Listening'));
端点。我希望它不会阻塞主线程并同时处理两个请求。相反,我在控制台中看到的是
/users
而不是
Server Listening
Start processing
Processing took 3007ms
Start processing
Processing took 3005ms
答案 0 :(得分:1)
我在我的机器上运行了你的代码并进行了类似的日志记录,但是我改变了一点,如下所示:
router.get('/users', function *() {
if (this.query.fast === '1'){
this.body = ['User 3', 'User 4']
}
else{
yield new Promise((resolve, reject) => {
setTimeout(() => resolve(this.body = ['User 1', 'User 2']), 5000);
});
}
});
然后我执行GET
到http://localhost:3000/users
等待在setTimeout中等待,然后我立即执行GET
到http://localhost:3000/users?fast=1
并立即返回结果。只是为了表明没有阻止。
$node server.js
Server Listening
Start processing
Start processing
Processing took 6ms
Processing took 5005ms
不太确定为什么日志会让线程看起来像是被阻止了,也许还有一些缓冲,但我认为它只会产生误导。
答案 1 :(得分:-1)
在URL的末尾添加查询字符串使其按预期工作。这让我觉得如果来自同一个IP地址,Koa可能阻止对同一实体的请求。
但这只是一种推测。