Skip to content

Instantly share code, notes, and snippets.

@ixti
Last active May 10, 2023 23:25
Show Gist options
  • Save ixti/c267775ab71c3843417f4eef4d164854 to your computer and use it in GitHub Desktop.
Save ixti/c267775ab71c3843417f4eef4d164854 to your computer and use it in GitHub Desktop.
Redis workbench (supports redis-rb only)
class RedisWorkbench
attr_accessor :logger
def initialize(redis_pool: ::Sidekiq.redis_pool, count: 1000, logger: Logger.new($stdout))
@redis_pool = redis_pool
@count = count.to_i
@logger = logger
end
# @example with block
# RedisWorkbench.new.each_key(match: "sessions:*") do |key|
# puts key
# end
#
# @example without block
# RedisWorkbench.new.each_key(match: "sessions:*").group_by do |key|
# key.split(":").second
# end
def each_key(match: nil, count: @count, &block)
return to_enum(__method__, match: match, count: count) unless block_given?
options = { count: count }
options[:match] = match.to_s if match
@redis_pool.with do |redis|
redis.scan_each(**options, &block)
end
self
end
# @example
# RedisWorkbench.new.delete_keys(match: "sessions:*")
def delete_keys(match:, count: @count)
deleted = 0
@redis_pool.with do |redis|
each_key(match: match, count: count).each_slice(count) do |keys|
redis.del(*keys)
deleted += keys.size
end
end
deleted
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment