njs 的这个 example 很有趣

2019-07-12 05:31:46 +08:00
 Livid

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);
}

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

3300 次点击
所在节点    NGINX
3 条回复
cnnblike
2019-07-12 06:38:43 +08:00
有种“睡眠排序”的感觉
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
2019-07-12 09:51:53 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/582207

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX