【问题标题】:Ruby on Rails always pointing local redis ServerRuby on Rails 总是指向本地 redis 服务器
【发布时间】:2014-01-26 13:06:56
【问题描述】:

我正在使用Redis 和我的ruby on rails application,使用redis-objectsdm-coredm-redis-adapter 将Ruby 对象映射到Redis。以下是代码片段

宝石文件

gem 'redis-objects'
gem "dm-core", "~> 1.2.1"
gem "dm-redis-adapter"

/config/initializers/redis.rb

// LOCAL REDIS SERVER
Redis.current = Redis.new(:host => '127.0.0.1', :port => 6379)
// REMOTE REDIS SERVER
#Redis.current = Redis.new(:host => '<VM IP>', :port => <VM PORT>, :password => '<PASSWORD>')

模型.rb

DataMapper.setup(:default, {:adapter  => "redis"})

class User
  include Redis::Objects
  include DataMapper::Resource

  include ActiveModel::Validations  
  include ActiveModel::Conversion  

  # datamapper fields, just used for .create
  property :id, Serial
  property :name, String
  property :email, String
  property :des, Text

  def id
    1
  end

end

User.finalize

本地 redis 服务器运行良好。为什么app总是指向本地redis,即使提供远程主机和端口?

已解决:查看我的答案。

【问题讨论】:

    标签: ruby-on-rails ruby redis redis-objects


    【解决方案1】:

    Redis.current 是一个在实例变量@current 为空时总是提供新连接的方法。见https://github.com/redis/redis-rb/blob/master/lib/redis.rb#L19

      def self.current
        @current ||= Redis.new
      end
    

    尝试将 Redis.new 分配给其他一些全局变量,例如 $redis。这应该主要解决您的问题。

    【讨论】:

    【解决方案2】:

    根据问题:

    // LOCAL REDIS SERVER
    Redis.current = Redis.new(:host => '127.0.0.1', :port => 6379)
    // REMOTE REDIS SERVER
    #Redis.current = Redis.new(:host => '<VM IP>', :port => <VM PORT>, :password => '<PASSWORD>')
    

    模型.rb

     DataMapper.setup(:default, {:adapter  => "redis"})
    

    在上面的代码中,我在用户模型中重载了 Redis 配置。 在这种情况下,我还需要在模型中编写远程配置。

    DataMapper.setup(:default, {:adapter  => "redis", :host => '<VM IP>', :port => <VM PORT>, :password => '<PASSWORD>'})
    

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 2020-06-04
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 2018-04-18
      相关资源
      最近更新 更多