Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
アクション別アクセスカウンタ(Redis版)
diff --git a/qualifier/webapp/ruby/app.rb b/qualifier/webapp/ruby/app.rb
index 4d64f98..0a45adf 100644
--- a/qualifier/webapp/ruby/app.rb
+++ b/qualifier/webapp/ruby/app.rb
@@ -8,6 +8,7 @@ require 'erubis'
require 'tempfile'
require 'redcarpet'
require 'rack/perftools_profiler'
+require 'redis'
class Isucon3App < Sinatra::Base
@@ -81,12 +82,46 @@ class Isucon3App < Sinatra::Base
def mem
@@mem ||= Dalli::Client.new("localhost:11212")
end
+
+ def redis
+ @@redis ||= Redis.new
+ end
end
post '/init' do
mem.set("public_count", 20540, nil, raw: true)
end
+ before do
+ @start = Time.now.to_f
+ end
+
+ after do
+ @stop = Time.now.to_f
+ redis.pipelined do |r|
+ r.hincrby "action_count", self.env['sinatra.route'], 1
+ r.hincrby "action_response", self.env['sinatra.route'], ((@stop - @start) * 1000).round # msec
+ end
+ end
+
+ get '/profile' do
+ response = ""
+ redis.hkeys("action_count").each do |key|
+ next if %r|/count$|.match(key)
+ count = redis.hget("action_count", key).to_i
+ sum_of_response = redis.hget("action_response", key).to_f / 1000
+ response += "%24s:%6d * %0.3f ms => %8.3f ms\n" % [key, count, sum_of_response / count, sum_of_response ]
+ end
+ response
+ end
+
+ delete '/profile' do
+ redis.hkeys("action_count").each do |key|
+ redis.del "action_count", key
+ redis.del "action_response", key
+ end
+ end
+
get '/' do
mysql = connection
user = get_user
@f440
Owner
f440 commented Nov 10, 2013

curl http://localhost/profile でアクセス回数、平均レスポンス時間、合計レスポンス時間を表示

      GET /memo/:memo_id:   302 * 0.010 ms =>    3.005 ms
                   GET /:   176 * 0.026 ms =>    4.546 ms

curl -X DELETE http://localhost/profile でリセット

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment