Last active
May 10, 2023 23:25
-
-
Save ixti/c267775ab71c3843417f4eef4d164854 to your computer and use it in GitHub Desktop.
Redis workbench (supports redis-rb only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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