You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ruby通过HMSET在Redis哈希中存储ActiveRecord缓存数据

Switching to HMSET for Redis Caching of ActiveRecord Data

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:03:25