簡體   English   中英

表達-一次將一個請求限制為一個

[英]express - Limit a request to one at a time

我正在使用express來構建應在內部使用的API。 請求之一觸發了服務器上的繁重進程,應從中返回CSV。 此過程可能需要10分鍾以上。

為了不使服務器超載,我想限制此API的調用並使之調用,從而使該進程不會終止,因此我們無法再次請求相同的URL。

為此,我嘗試通過以下配置使用express-rate-limit

new RateLimit({
    windowMs: 30 * 60 * 1000, // 30 minutes
    max: 1,
    delayMs: 0, // disabled
    message: 'Their is already a running execution of the request. You must wait for it to be finished before starting a new one.',
    handler: function handler(req, res) {
        logger.log('max request achieved');
        logger.log(res);
    },
});

但是,即使我只啟動一次,似乎也要在2分鍾后每次都達到“最大請求”。 我懷疑瀏覽器在2分鍾后仍未收到任何答復,是否可以重試該請求,這可能嗎?

我希望此請求沒有任何retry-strategy並且達到max request的唯一方法是手動要求服務器連續兩次執行此請求。

謝謝。


編輯

這是我的完整代碼:

const app = express();
const port = process.env.API_PORT || 3000;

app.enable('trust proxy');

function haltOnTimedout(req, res, next) {
    if (!req.timedout) { next(); }
}

app.use(timeout(30 * 60 * 1000)); // 30min
app.use(haltOnTimedout);

app.listen(port, () => {
    logger.log(`Express server listening on port ${port}`);
});

// BILLING
const billingApiLimiter = new RateLimit({
    windowMs: 30 * 60 * 1000, // 30 minutes
    max: 1,
    delayMs: 0, // disabled
    message: 'Their is already a running execution of the request. You must wait for it to be finished before starting a new one.',
    handler: function handler(req, res) {
        logger.log('max request achieved');
    },
});

app.use('/billing', billingApiLimiter);
app.use('/billing', BillingController);

和我的route的代碼:

router.get('/billableElements', async (request, response) => {
    logger.log('Route [billableElements] called');
    const { startDate } = request.query;
    const { endDate } = request.query;
    try {
        const configDoc = await metadataBucket.getAsync(process.env.BILLING_CONFIG_FILE || 'CONFIG_BILLING');
        const billableElements = await getBillableElements(startDate, endDate, configDoc.value);
        const csv = await produceCSV(billableElements);
        logger.log('csv produced');
        response.status(200).send(`${csv}`);
    } catch (err) {
        logger.error('An error occured while getting billable elements.', err);
        response.status(500).send('An internal error occured.');
    }
});

我找到了這個GitHub問題的答案謝謝: https : //github.com/expressjs/express/issues/2512

TLDR:我添加了request.connection.setTimeout(1000 * 60 * 30); 以避免每2分鍾觸發一次請求。

但是考慮到我在問題中編寫的代碼,@ Paul的建議仍然值得考慮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM