并发给hapijsv20处理程序的并发请求的请求

问题描述

我有一个使用HapiJS框架开发的API。如果处理程序返回承诺,则后续请求将等待完成现有请求。所以基本上我在访问API时正在执行异步过程。

请找到以下示例:

// Server Creation ...

// Route Creation
server.route({
    method: 'GET',path: '/v1/check',handler: () => {
        console.log('Check');

        return new Promise((resolve) => {
            setTimeout(() => {
                console.log('Check Response')
                resolve({check: 1});
            },1000);

        });
    }
});

在浏览器的3个不同选项卡中执行相同的路由并同时全部重新加载时。

日志:

Check
Check Response
Check
Check Response
Check
Check Response

预期日志:

Check
Check
Check
Check Response
Check Response
Check Response
// Not expecting the same log,but wanted parallel execution.

所以我的疑问是,如果100个用户使用相同的API,那么第100个请求必须等待99个请求完成?

输出有些混淆。

解决方法

使用浏览器进行测试可能并不理想,因为它们通常会限制允许的并发连接数量。

当我使用Apache Bench运行示例时,得到了预期的结果。

服务器:

'use strict';

const Hapi = require('@hapi/hapi');

const init = async () => {

    const server = Hapi.server({
        port: 3000,host: 'localhost'
    });

    server.route({
        method: 'GET',path: '/v1/check',handler: () => {
            console.log('Check');
    
            return new Promise((resolve) => {
                setTimeout(() => {
                    console.log('Check Response')
                    resolve({check: 1});
                },1000);
    
            });
        }
    });

    await server.start();
    console.log('Server running on %s',server.info.uri);
};

init();

测试:

 docker run -it --net="host" --rm -t devth/alpine-bench -n10 -c10 http://host.docker.internal:3000/v1/check

结果:

$ node index.js
Server running on http://localhost:3000
Check
Check
Check
Check
Check
Check
Check
Check
Check
Check
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...