how to count number of requests in last second, minute and hour

后端 未结 10 2035
情歌与酒
情歌与酒 2020-12-07 09:35

There is a hypothetical web server which supports only one very simple API - count of requests received in the last hour, minute and second. This server is very popular in t

10条回答
  •  失恋的感觉
    2020-12-07 10:21

    Following code is in JS. It will return you the count in O(1). I wrote this program for an interview where time was pre defined to be 5 minutes. But you can modify this code for seconds, minutes, and so on. Let me know how it goes.

    1. Create an Object that will have milliseconds as key and counter as value
    2. Add a property called totalCount and predefine it to be 0
    3. With each log of hits increment counter defined in step 1 and the totalCount
    4. Add a method called clean_hits, call this method every millisecond
    5. In clean_hits method remove each entry (outside our time range) from the object that we created and subtract that count from totalCount before you delete the entry

      this.hitStore = { "totalCount" : 0};

提交回复
热议问题