【问题标题】:Cache API responses until told to release?缓存 API 响应直到被告知释放?
【发布时间】:2015-10-11 03:26:39
【问题描述】:

我有以下型号:

class User < ActiveRecord::Base
  def stripe_plan_id
    self.stripe_subscription.plan.id
  end

  def stripe_subscription
    customer = Stripe::Customer.retrieve(self.stripe_customer_id)
    customer.subscriptions.retrieve(self.stripe_subscription_id)
  end
end

我有模型属性stripe_plan_id 我不希望它使用ActiveRecord 持久化到数据库中,但是我需要经常检查这个参数。我想将它缓存在我的服务器上,并根据需要刷新它。理想情况下我不想使用redis。

最好的方法是什么?我正在尝试确定是否可以以某种方式使用||=。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 caching


    【解决方案1】:

    有很多方法,我假设您知道如何使用您拥有的任何东西(memcached、redis、rails.cache 等)进行缓存,如果不是这样,请告诉我。我建议创建一个基于 id 获取或重新加载缓存的缓存类。您的记忆不适用于您的情况,因为您希望在控制器之间持续存在。

    def StripeCache < Struct.new(:user)
    
      def cache_key
        "#{user.id}_stripe_plan_id"
      end 
    
      def get
        ReadFromCache(cache_key)
      end
    
      def reload
        WriteToCache(cache_key, user.stripe_plan_id)
      end
    end
    

    然后当你想得到这个时,你只需调用

    StripeCache.new(user).get
    

    并保存您调用的新内容

    StripeCache.new(user).reload
    

    有点额外的开销,但会从你那里抽象出所有对缓存的读写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2021-09-28
      相关资源
      最近更新 更多