服务器问答

njs 的这个 example 很有趣
0
2021-05-19 16:22:56
idczone

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

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


有种“睡眠排序”的感觉

现在有新的写法了:
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。

想起了这个 https://talks.golang.org/2012/concurrency.slide#48

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服