请求缓冲区

Buffer of requests

我已经使用 Node 和 ExpressJS 开发了一个 REST-API,我需要创建一个临时缓冲区来比较 X 秒内请求接收的数据。

例如,服务器接收到请求,将其存储在缓冲区中并启动计时器。虽然计时器未完成,但所有请求数据也将存储在该缓冲区中。计时器完成后,我需要比较缓冲区内的所有数据,然后将其发送到数据库。

我的问题是我不知道是否可以使用 node 和 express 来实现,我搜索了但没有找到适合我的解决方案。也许有人可以帮助我解决我的问题。谢谢。

我确定有库可以做到这一点,但如果您想自己实现它,您可以这样做:

你可以写一个小的 Request-Recorder class 公开一个 recordData 方法,它允许你记录请求数据,如果记录器当前是活动的或者没有记录任何数据还。如果是后一种情况,则启用计时器并让它记录数据,直到达到超时为止。像这样的东西应该可以帮助你开始:

class RequestDataRecorder {
    static instance;

    constructor() {
        this.isActive = false;
        this.isLocked = false;
        // could also be a map, holding request data by request-id for example
        this.recordedData = [];
        this.recordDataDurationInSeconds = 10; // will capture request data within 10 second time frames
    }

    static shared() {
        if (!RequestDataRecorder.instance) {
            RequestDataRecorder.instance = new RequestDataRecorder();
        }
        return RequestDataRecorder.instance;
    }

    recordData(data) {
        if (this.canActivate()) {
            this.activate();
        }
        if (this.isCurrentlyActive()) {
            this.recordedData.push(data);
        }
    }

    canActivate() {
        return !this.isLocked && !this.isActive && this.recordedData.length === 0;
    }

    activate() {
        this.isLocked = true;
        this.timer = setTimeout(() => {
                this.deactivate();
                this.exportData();
            }, this.recordDataDurationInSeconds * 1000);
        this.isLocked = false;
        this.setActive(true);
    }

    deactivate() {
        this.isLocked = true;
        this.setActive(false);
        clearTimeout(this.timer);
        this.recordedData = [];
        this.isLocked = false;
    }

    setActive(val) {
        this.isActive = val;
    }

    isCurrentlyActive() {
        return this.isActive;
    }

    exportData() {
        // do your db-export here or use another class to to the export with this data (preferably the latter to comply with the single-responsibilty principle :))
        return this.recordedData;
    }

}

您可以这样使用 class:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
const requestDataRecorder = RequestDataRecorder.shared();

app.post("/postSomeData", (req, res) => {
    requestDataRecorder.recordData(req.body);
    res.status(201).end();
});

app.get("/getRecordedData", (req, res) => {
    res.send(requestDataRecorder.getRecordedData());
});

app.listen(3000, function () {
    console.log("Server is listening!");
});