【问题标题】:Concurrent request to hapijs(v20) handler which returns promise对返回承诺的 hapijs(v20) 处理程序的并发请求
【发布时间】:2020-10-07 17:47:37
【问题描述】:

我有一个使用 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 个请求的完成?

对输出有点困惑。

【问题讨论】:

    标签: node.js hapijs


    【解决方案1】:

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

    当我使用 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
    

    【讨论】:

      猜你喜欢
      • 2014-12-28
      • 1970-01-01
      • 2017-05-15
      • 2018-04-10
      • 2017-02-22
      • 2020-12-20
      • 1970-01-01
      • 2019-01-24
      相关资源
      最近更新 更多