V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
Livid
V2EX  ›  NGINX

njs 的这个 example 很有趣

  •  
  •   Livid · 2019-07-12 05:31:46 +08:00 · 3276 次点击
    这是一个创建于 1722 天前的主题,其中的信息可能已经有所发展或是发生改变。

    http://nginx.org/en/docs/njs/examples.html

    Returning Fastest Response from Proxy

    nginx.conf

    js_include fastresponse.js;
    
    location /start {
        js_content content;
    }
    
    location /foo {
        proxy_pass http://backend1;
    }
    
    location /bar {
        proxy_pass http://backend2;
    }
    

    fastresponse.js:

    function content(r) {
        var n = 0;
    
        function done(res) {
            if (n++ == 0) {
                r.return(res.status, res.responseBody);
            }
        }
    
        r.subrequest('/foo', r.variables.args, done);
        r.subrequest('/bar', r.variables.args, done);
    }
    

    利用异步调用的特性,谁先返回谁就是最快的。虽然可能有点浪费资源,但是这个思路实在是很有趣。

    3 条回复    2019-07-12 09:51:53 +08:00
    cnnblike
        1
    cnnblike  
       2019-07-12 06:38:43 +08:00
    有种“睡眠排序”的感觉
    Mutoo
        2
    Mutoo  
       2019-07-12 06:49:57 +08:00
    现在有新的写法了:

    function content(r) {
    ...
    return Promise.race([resouce1, resource2]);
    }

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

    但是因为 promise 是 non-cancellable 的,如果有更多的资源进行 race 就会造成浪费。
    未来会有 cancellabel-promise 来解决这个问题,并且会有短路类型的 race-like 加入 promise。
    SakuraKuma
        3
    SakuraKuma  
       2019-07-12 09:51:53 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5911 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 02:09 · PVG 10:09 · LAX 19:09 · JFK 22:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.