简体   繁体   English

如何在使用Rack Cache时跟踪API请求的数量

[英]How to track number of API requests when using Rack Cache

I will be using Rack Cache (with Memcache) to cache responses from an API I am building with Rails. 我将使用Rack Cache(带Memcache)来缓存我正在使用Rails构建的API的响应。 In addition, I need to implement hit counting for the API. 另外,我需要为API实现命中计数。 Any suggestions on to pull this off? 有什么建议可以解决这个问题吗? I am guessing it would need to be handled with Rack, but am not sure where to start. 我猜它需要用Rack处理,但我不知道从哪里开始。 Thanks! 谢谢!

I would suggest adding a piece of Rack middleware to the top of your middleware stack which increments a counter for the request path. 我建议将一个Rack中间件添加到中间件堆栈的顶部,这会增加请求路径的计数器。

For example, to do this with Redis: 例如,要使用Redis执行此操作:

# lib/request_counter.rb
class RequestCounter
  def self.redis
    @redis ||= Redis.new(host: ENV["REDIS_HOST"], port: ENV["REDIS_PORT"])
  end

  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    self.class.redis.incr "request_counter:#{request.fullpath}"
    @app.call(env)
  end
end

# config/application.rb (in the Rails::Application subclass)
require "request_counter"
config.middleware.insert(0, RequestCounter)

This would mean that each request to /path would increment the Redis key request_counter:/path 这意味着对/path每个请求都会增加Redis密钥request_counter:/path

Depending on your production setup, you might be able to do this in one of the following ways 根据您的生产设置,您可以通过以下方式之一执行此操作

  • parse nginx logs, either with your own scripts or using splunk ( example ) 解析nginx日志,使用您自己的脚本或使用splunk( 示例
  • write your own nginx module to do the counting 编写自己的nginx模块来进行计数
  • attach your own Rack middleware before Rack::Cache to do the counting ( guides ) 在Rack :: Cache之前连接你自己的Rack中间件来进行计数( 指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM