Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

การลบ Hashes ขนาดใหญ่ใน Redis: แนวทางปฏิบัติที่ดีที่สุด

เพื่อเรียนรู้เพิ่มเติมเกี่ยวกับเหตุผลที่การลบออบเจ็กต์ขนาดใหญ่ช้าใน Redis อ่านภาพรวมสั้นๆ นี้

เพื่อลบ Hash ขนาดใหญ่ใน Redis:

  1. เปลี่ยนชื่อคีย์เป็นคีย์เฉพาะที่มี namespace เพื่อให้ Hash ปรากฏว่า "ถูกลบ" แก่ Redis clients อื่นๆ ทันที

  2. ลบ fields จาก Hash แบบเพิ่มทีละน้อยในแบทช์เล็กๆ จนว่าจะว่างเปล่า โดยจำกัดขนาดคำสั่งลบ เรา确保ว่าไม่บล็อกเซิร์ฟเวอร์นานเกินไป

โปรดทราบว่าโค้ดต่อไปนี้ไม่จัดการ Redis connection failures อย่างยืดหยุ่น หากคำสั่ง Redis ใดล้มเหลวและโยน exception คุณจะต้องทำความสะอาดด้วยตนเอง

Pseudo-code

# เปลี่ยนชื่อคีย์ newkey = "gc:hashes:" + redis.INCR("gc:index") redis.RENAME("my.hash.key", newkey) # ลบ fields จาก hash ในแบทช์ของ 100 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

Ruby

$redis = Redis.new def delete_hash(key) # เปลี่ยนชื่อคีย์ newkey = "gc:hashes:#{$redis.incr("gc:index")}" $redis.rename(key, newkey) # ลบ fields จาก hash ในแบทช์ของ 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 # ตัวอย่าง: # # delete_hash("my.large.hash")

นี่คือตัวอย่างการนำไปใช้งานข้างต้นด้วย background jobs ใน Ruby:

  • Resque
  • Sidekiq

← กลับไป "Deleting Large Objects in Redis"