0

为了避免不寻常的数据存储,我想限制我的服务器在给定时间段内接受的 HTTP 请求的数量,例如最多每十秒一次。实际上,如果每个周期有太多 HTTP 请求,我想使我的控制器操作以错误消息响应。我怎么能/应该这样做?它应该在中间件中处理吗?


更新

我正在寻找一种方法来使控制器操作为传入的 HTTP 请求运行。然后,在控制器操作代码中,我想检查最后一个资源对象是否在过去 10 秒内被访问(通过 HTTP 请求),我想比较最后一个 HTTP 请求的时间使用存储在该资源对象的数据库中的“日志时间”执行

“log-time”是与上述资源对象(Ruby on Rails ActiveModel 对象)相关的一个属性,它旨在存储该对象的最后一次访问时间(通过 HTTP 请求)。因此,如果每个时间段对该资源对象执行了太多 HTTP 请求,那么我想生成一个错误。

4

1 回答 1

2

This might be better handled by Nginx or Apache. Not every HTTP requests goes through your Rails application. For example, requests for static assets are often handled by Nginx/Apache directly. Moreover, as you scale your application, you might eventually have multiple Rails processes behind the same nginx server.

For nginx, the HttpLimitReqModule might be what you need. When the limit is exceeded, the server will respond with 503 Service Temporarily Unavailable. A custom error page can be created for this status code.

For apache, there is mod_ratelimit and mod_evasive.

(This might be obvious, but an additional advantage of handling rate limits in nginx/apache is that requests over the limit don't even go into your Rails processes. Nginx/Apache will cut them off immediately, potentially saving some CPU.)

于 2013-08-06T19:57:27.033 回答