应用程序重启时,Redis数据重置为默认值

时间:2015-06-23 10:46:35

标签: ruby-on-rails redis

我在初始化程序中将Redis实例化为:

uri = URI.parse(ENV["REDISTOGO_URL"] || "redis://localhost:6379/")

KEYS = %w(
    first_attempt_success
    first_attempt_failure
    first_retry_success
    first_retry_failure
  )

  unless $stats
    $stats = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
    KEYS.map { |k| $stats.set(k, 0) }
  end

然后我继续在我的模型中使用它,如下所示:

class StatsCounter

  KEYS = %w(
    first_attempt_success
    first_attempt_failure
    first_retry_success
    first_retry_failure
  )

  def self.stats
    uri = URI.parse(ENV["REDISTOGO_URL"] || "redis://localhost:6379/")
    unless $stats
      $stats = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
      KEYS.map { |k| $stats.set(k, 0) }
    end
    $stats
  end

  def self.get_stats
    Hash[KEYS.collect { |k| [k, stats.get(k)] }]
  end
end

但我遇到的问题是,每次重新启动服务器时 - (重新启动应用程序),Redis实例中保存的所有数据都会重置为零。 我知道Redis是一个内存数据库。 我该怎么做,以便即使应用程序重新启动,我的数据仍然存在? 感谢

1 个答案:

答案 0 :(得分:0)

所以,我认为我找到了可能导致这种情况的原因,也解决了它。 通过替换这个:    KEYS.map {| k | $ stats.set(k,0)} 使用一个简单的三元组来检查特定的Redis键是否已设置如下: KEYS.map {| k | $ stats.get(k)? true:$ stats.set(k,0)} 每次应用程序重新启动时,我都能阻止我的数据重置为0默认值。 谢谢大家。