如何使用Rails.cache.fetch实现API JSON响应缓存(无需额外库)
Got it! Let's get you set up with Rails' built-in low-level caching for that API response—no extra gems needed. Here's how to make it work smoothly:
Rails.cache.fetch First, wrap your existing API request logic inside Rails.cache.fetch. This method checks for cached data first: if it exists, it returns immediately; if not, it runs your API call, stores the result in the cache, and returns it.
Basic Example
def fetch_api_data # Create a unique cache key—add parameters here if your API call uses them cache_key = "external_api_weather_data_v1" # Set an expiration time matching how often the API data updates (e.g., 24 hours) Rails.cache.fetch(cache_key, expires_in: 24.hours) do # Your existing API request code goes here (Faraday, Net::HTTP, etc.) response = Faraday.get("https://your-api-endpoint.com/data") JSON.parse(response.body) # Parse the JSON into a Ruby hash/array end end
Key Tips for Success
Smart Cache Keys: If your API call uses dynamic parameters (like user IDs or location filters), include them in the cache key to avoid mixing up cached results:
cache_key = "external_api_user_data_#{user.id}_v1"Adding a version suffix (like
_v1) lets you invalidate all old cache entries easily if the API response structure changes later.Handle API Failures: Don't cache error responses—add a check to ensure you only store valid data:
Rails.cache.fetch(cache_key, expires_in: 12.hours) do response = Faraday.get("https://your-api-endpoint.com/data") if response.success? JSON.parse(response.body) else # Return a default value or raise an exception based on your needs {} end endManual Cache Invalidation: If the API data updates unexpectedly, you can manually clear the cache for a specific key:
Rails.cache.delete("external_api_weather_data_v1")Configure Cache Storage: Make sure your Rails app uses an appropriate cache store. For development, the default
:memory_storeworks fine. For production, set up Redis (recommended) inconfig/environments/production.rb:config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"] }
This approach uses only Rails' built-in tools, so you won't need to add any extra third-party libraries—perfect for avoiding those API request limits!
内容的提问来源于stack exchange,提问作者mrdmr

