3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ruby の TCPSocket クラスで memcached のメモリに関する情報を取得する

Last updated at Posted at 2024-11-12

やりたいこと

memcached のメモリに関する情報を取得するには stats コマンドを使用する。例えばターミナルでは以下のように行う。

$ echo stats | nc -w 1 localhost 11211 | awk '$2 ~ /bytes/ { print $2": "$3 }'
bytes_read: 17492988
bytes_written: 370282118
limit_maxbytes: 3212836864
hash_bytes: 524288
bytes: 523087
  • memcached がデフォルトで使用するポート番号は 11211
  • bytes: 523087 が使用しているメモリのサイズ

Ruby でも同様のことを行いたい。

方法

TCPSocket クラスを使用する。

require 'socket'

HOST = 'localhost'
PORT = 11_211

socket = TCPSocket.open(HOST, PORT)
stats = {}

begin
  socket.puts('stats')

  loop do
    line = socket.gets.chomp
    break if line == 'END'

    key, value = line.match(/STAT (?<key>\w+) (?<value>\d+)/).values_at(:key, :value)
    next unless key.include?('bytes')

    stats[key.to_sym] = value.to_i
  end
ensure
  socket.close
end

stats
#=>
# {:response_obj_bytes=>32768,
#  :read_buf_bytes=>81920,
#  :read_buf_bytes_free=>32768,
#  :bytes_read=>17492988,
#  :bytes_written=>370282118,
#  :limit_maxbytes=>3212836864,
#  :launch_time_maxbytes=>3212836864,
#  :hash_bytes=>524288,
#  :bytes=>523087}

なお Active Support コア拡張機能String#to_fs を使うとサイズの数値が読みやすくなる。第 1 引数に :human_size を指定する。

require 'active_support'
require 'active_support/core_ext/numeric/conversions'

stats.transform_values { _1.to_fs(:human_size, locale: :en) }
#=>
# {:response_obj_bytes=>"32 KB",
#  :read_buf_bytes=>"80 KB",
#  :read_buf_bytes_free=>"32 KB",
#  :bytes_read=>"16.7 MB",
#  :bytes_written=>"353 MB",
#  :limit_maxbytes=>"2.99 GB",
#  :launch_time_maxbytes=>"2.99 GB",
#  :hash_bytes=>"512 KB",
#  :bytes=>"511 KB"}

バージョン情報

$ ruby --version
ruby 3.3.6 (2024-11-05 revision 75015d4c1f) [arm64-darwin24]

$ echo version | nc -w 1 localhost 11211 # memcached
VERSION 1.6.17

$ gem list | grep activesupport
activesupport (8.0.0)

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?