如何为caches_action配置多cache_store,指定非默认Redis服务器
如何配置多缓存存储并在控制器动作中指定使用
这个需求在Rails里实现起来很清晰,分两步就能搞定:先注册多个缓存实例,再在控制器里指定动作使用目标缓存。
1. 在配置文件中注册多缓存存储
首先在config/application.rb或者对应环境的配置文件(比如config/environments/production.rb)里,除了设置默认缓存,还要用config.cache_stores(复数形式)注册额外的Redis服务器:
# config/application.rb # 默认全局使用的Redis缓存 config.cache_store = :redis_store, "redis://localhost:6379/0", { expires_in: 90.minutes } # 注册第二个Redis缓存实例,命名为:product_specific_redis config.cache_stores[:product_specific_redis] = :redis_store, "redis://another-redis-server:6379/1", { expires_in: 1.hour, namespace: "product_cache" # 可选,给缓存键加命名空间,避免和默认缓存冲突 }
如果你的Rails版本低于5.2(不支持config.cache_stores),可以手动创建缓存实例并保存为常量,放在config/initializers/cache_stores.rb里:
ProductSpecificRedisCache = ActiveSupport::Cache.lookup_store( :redis_store, "redis://another-redis-server:6379/1", expires_in: 1.hour, namespace: "product_cache" )
2. 在控制器中指定动作使用特定缓存
在ProductsController的caches_action调用里,通过cache_store参数直接指定我们注册好的缓存实例就行:
Rails 5.2+版本写法
class ProductsController < ApplicationController # 给show动作指定使用:product_specific_redis缓存,还能单独设置过期时间 caches_action :show, cache_store: :product_specific_redis, expires_in: 30.minutes def show @product = Product.find(params[:id]) end end
低版本Rails写法(用常量)
class ProductsController < ApplicationController caches_action :show, cache_store: ProductSpecificRedisCache, expires_in: 30.minutes def show @product = Product.find(params[:id]) end end
额外小提示
- 注册好的缓存实例可以在其他地方复用,比如手动缓存数据:
# 5.2+版本 Rails.cache_stores[:product_specific_redis].write("product_#{@product.id}", @product, expires_in: 1.hour) # 低版本 ProductSpecificRedisCache.write("product_#{@product.id}", @product, expires_in: 1.hour) - 如果需要更灵活的缓存逻辑,也可以放弃
caches_action,在动作里手动处理缓存:def show cache_key = "product_show_#{params[:id]}" @product = Rails.cache_stores[:product_specific_redis].fetch(cache_key, expires_in: 30.minutes) do Product.find(params[:id]) end end
内容的提问来源于stack exchange,提问作者edenisn
相关产品推荐
相关产品推荐

