`
robbin
  • 浏览: 4799034 次
  • 性别: Icon_minigender_1
  • 来自: 上海
博客专栏
377a9ecd-1ea1-34ac-9530-9daa53bb2a7b
robbin谈管理
浏览量:135736
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
memcached ruby client ruby, memcached
#!/usr/bin/env ruby
require 'socket'

# stats
# stats reset
# stats malloc
# stats maps
# stats sizes
# stats slabs
# stats items
# stats cachedump slab_id limit_num
# stats detail [on|off|dump]

class Memcache
  class << self
    def open(host, port)
      s = TCPSocket.open(host, port)
      yield s if block_given?
    ensure
      s.close if s
    end
  
    def command(command_string, s)
      s.send(command_string + "\r\n", 0)
      buff = []
      until ["END", "OK", "DELETE", "ERROR"].include?(line = s.gets.strip) do
        buff << line 
      end
      buff
    end
  
    def exec(command_string, host = "localhost", port = 11211)
      open(host, port) { |socket| command(command_string, socket).each {|line| puts line } }
    end
    
    def hit_rate(host = "localhost", port = 11211)
      cmd_get = 0; get_hits = 0; time_seconds = 0
      open(host, port) do |socket|
        command("stats", socket).each do |line|
          stats = line.split
          time_seconds = stats[2] if stats[1] == 'uptime'
          cmd_get = stats[2] if stats[1] == 'cmd_get'
          get_hits = stats[2] if stats[1] == 'get_hits'
        end
      end
      puts "Cmd GET: #{cmd_get}\t GET Hits: #{get_hits}"
      puts "#{cmd_get.to_i/time_seconds.to_i} Cache GET per second"
      puts "Hit rate: #{((get_hits.to_f/cmd_get.to_f)*100).round(1)}%"
    end
        
    def monitor(duration, host = "localhost", port = 11211)
      open(host, port) do |socket|
        #command("stats detail on", socket)
        #sleep duration
        #command("stats detail off", socket)
        command("stats detail dump", socket).each {|line| puts line}
      end
    end
    
    def cache_stats(host = "localhost", port = 11211)
      cache_objects = {}
      open(host, port) do |socket|
        slabs = []
        command("stats items", socket).each do |line|
          slab_id = line.split[1].split(":")[1].to_i
          slabs << slab_id unless slabs.include?(slab_id)
        end
        slabs.each do |slab_id|
          puts "browse slab #{slab_id}..."
          command("stats cachedump #{slab_id} 0", socket).each do |item|
            key = item.split[1].split("/")[0].to_s
            cache_objects.include?(key) ? cache_objects[key] += 1 : cache_objects[key] = 1
          end
        end
      end
      cache_objects.each_pair {|key, value| puts "#{key} : #{value}"}
    end
  end
end

if ARGV.size == 0
  Memcache.hit_rate
elsif ARGV.size == 1 && ARGV[0].to_i > 0
  Memcache.monitor ARGV[0].to_i
else
  Memcache.exec(ARGV.join(" "))
end
hello ruby
#!/usr/bin/env ruby

puts "Hello World!"
Global site tag (gtag.js) - Google Analytics