redis无法连接到rails(ECONNREFUSED)

时间:2016-06-02 23:48:45

标签: ruby-on-rails redis

了解在Rails中执行自动填充建议的不同方法。现在,尝试基于Railscast 399的Redis,并且rake任务停止工作。

控制器:

class VenueSuggestionsController < ApplicationController
  def create
    VenueSuggestion.create(params[:venue_suggestion])
  end

  def index
    render json: VenueSuggestion.terms_for(params[:term])
  end

  private
        def venue_suggestion_params
            params.require(:venue_suggestion).permit(:term, :popularity, venues_attributes: [ :id, :name, :address ])
        end
end

模型

class VenueSuggestion
  def self.terms_for(prefix)
    $redis.zrevrange "venue-suggestions:#{prefix.downcase}", 0, 9
  end

  def self.index_venues
    Venue.find_each do |venue|
      index_term(venue.name)
      index_term(venue.address)
      venue.name.split.each { |t| index_term(t) }
    end
  end

  def self.index_term(term)
    1.upto(term.length-1) do |n|
      prefix = term[0, n]
      $redis.zincrby "venue-suggestions:#{prefix.downcase}", 1, term.downcase
    end
  end
end

rake任务:

namespace :venue_suggestions do
  desc "Generate venue suggestions for event form"
  task :index => :environment do
    VenueSuggestion.index_venues
  end
end

配置/初始化/ redis.rb

$redis = Redis.new

然后尝试运行它:

$ rake venue_suggestions:index --trace
** Invoke venue_suggestions:index (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute venue_suggestions:index
rake aborted!
Redis::CannotConnectError: Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)

1 个答案:

答案 0 :(得分:2)

也许,您要做的是在后台运行您的redis服务器。

简易方法(Tm)

redis-server &

正确方式(Tm)

# cd into your redis directory(path for mine on OSX below)
cd /usr/local/etc/redis.conf
vim redis.conf
daemonize yes # find this line and change 'no' to 'yes'

然后重新启动redis服务器。

此外,这里有一些特定于OSX的有用说明(如果这是您的平台): https://medium.com/@petehouston/install-and-config-redis-on-mac-os-x-via-homebrew-eb8df9a4f298#.mc9tqg22p