Reputation: 3187
I will be using Rack Cache (with Memcache) to cache responses from an API I am building with Rails. In addition, I need to implement hit counting for the 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. Thanks!
Upvotes: 4
Views: 986
Reputation: 2532
I would suggest adding a piece of Rack middleware to the top of your middleware stack which increments a counter for the request path.
For example, to do this with 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
Upvotes: 5
Reputation: 13054
Depending on your production setup, you might be able to do this in one of the following ways
Upvotes: 1