Computer >> 컴퓨터 >  >> 프로그램 작성 >> Redis

Redis에서 큰 해시 삭제

Redis에서 큰 개체 삭제가 느린 이유에 대해 자세히 알아보려면 이 빠른 개요를 읽어보세요.

Redis에서 큰 해시를 삭제하려면:

  1. 해시가 다른 Redis 클라이언트에 즉시 "삭제"된 것처럼 보이도록 키 이름을 고유한 네임스페이스 키로 변경합니다.

  2. 비어 있을 때까지 해시에서 필드를 조금씩 삭제합니다. 삭제 명령의 크기를 제한하여 서버를 너무 오랫동안 차단하지 않도록 합니다.

다음 코드는 Redis 연결 실패를 정상적으로 처리하지 않습니다. Redis 명령이 실패하고 예외가 발생하면 수동으로 정리해야 합니다.

의사 코드

# Rename the key
newkey = "gc:hashes:" + redis.INCR( "gc:index" )
redis.RENAME("my.hash.key", newkey)

# Delete fields from the hash in batche of 100s
cursor = 0
loop
  cursor, hash_keys = redis.HSCAN(newkey, cursor, "COUNT", 100)
  if hash_keys count > 0
    redis.HDEL(newkey, hash_keys)
  end
  if cursor == 0
    break
  end
end

루비

$redis = Redis.new

def delete_hash(key)
  # Rename the key
  newkey = "gc:hashes:#{$redis.incr("gc:index")}"
  $redis.rename(key, newkey)

  # Delete fields from the hash in batches of 100
  cursor = "0"
  loop do
    cursor, fields = $redis.hscan(newkey, cursor, count: 100)
    hkeys = fields.map { |pair| pair[0] }
    $redis.hdel(newkey, hkeys) if hkeys.size > 0
    break if cursor == "0"
  end
end

# Example:
#
#   delete_hash("my.large.hash")

다음은 백그라운드 작업 inRuby를 사용하여 위의 몇 가지 구현 예입니다.

  • 요청
  • 사이드키크

← "Redis에서 큰 개체 삭제"로 돌아가기