如何使用Ruby通过HMSET在Redis哈希中存储ActiveRecord缓存数据
Got it, let's adjust your current Redis caching setup from basic SET/GET to using HMSET (or the recommended HSET for newer Redis versions). Here's a practical implementation that keeps your workflow intact while leveraging Redis hash structures:
Step 1: Understand the Hash Structure
Instead of storing all authors as a single JSON string under one key, we'll use a Redis hash where:
- The top-level key remains
authors - Each field in the hash is an author's ID (as a string)
- Each value is the JSON-serialized data of that author
This approach lets you update individual author entries later without re-caching the entire list—way more efficient!
Step 2: Updated Helper Code
Modify your authors_helper.rb like this:
def fetch_authors # Fetch all entries from the Redis hash authors_cache = $redis.hgetall('authors') if authors_cache.empty? # Cache miss: pull data from DB authors = Author.all # Build a hash mapping author IDs to their JSON data author_entries = authors.each_with_object({}) do |author, hash| hash[author.id.to_s] = author.to_json end # Use HMSET to populate the Redis hash (flatten the hash into key-value pairs) $redis.hmset('authors', *author_entries.flatten) # Set expiration for the entire hash key (same 5-hour window as before) $redis.expire('authors', 5.hour.to_i) # Return the fresh DB records authors else # Cache hit: parse JSON values and return as an array of author data authors_cache.values.map { |json| JSON.parse(json) } end end
Notes for Redis Versions 4.0+
HMSET has been deprecated in newer Redis versions in favor of HSET, which supports setting multiple field-value pairs directly. If you're running Redis 4.0 or later, you can replace the hmset line with:
# Directly pass the hash to HSET (Ruby client handles the conversion) $redis.hset('authors', author_entries)
Bonus: Updating Individual Authors
One of the perks of using a hash is being able to update a single author's cache without reloading the whole list. For example:
def update_author_cache(author) $redis.hset('authors', author.id.to_s, author.to_json) end
This keeps your cache fresh for specific entries without wasting resources on re-caching everything.
内容的提问来源于stack exchange,提问作者user3576036

