简体   繁体   English

在初始化时配置Redis连接

[英]Configure Redis connection on initialize

I'm using Predictor gem and when I attempt to start the gem shows: 我正在使用Predictor gem,并且在尝试启动gem时显示:

"redis not configured! - Predictor.redis = Redis.new" (RuntimeError)

So, how to configure Redis Connection on initialize? 那么,如何在初始化时配置Redis Connection

thank's 谢谢

This is how Redis is initialized in general. 通常,这就是Redis初始化的方式。

Firstly, a good practice would be adding this to your config/environments/[environment_name].rb . 首先,一个好的做法是将其添加到您的config/environments/[environment_name].rb So you can maintain different locations for Redis when you change environments. 因此,当您更改环境时,可以为Redis维护不同的位置。

config.redis_host   = "localhost"

Then in your application's config/initializers path create redis.rb and place the code below to initialize Redis . 然后在应用程序的config/initializers路径中创建redis.rb并将代码放置在下面以初始化Redis

require 'redis'

## Added rescue condition if Redis connection is failed
begin
  $redis = Redis.new(:host => Rails.configuration.redis_host, :port => 6379) 
rescue Exception => e
  puts e
end

Then you'll be able to use the global variable $redis within your application for Redis -related commands. 然后,您将可以在应用程序中使用全局变量$redis来执行与Redis相关的命令。

$redis.hset "my_hash", item.id, business.id

Here is a helpful article with more details. 是一篇有用的文章,其中包含更多详细信息。


Now in your case as this documentation suggests, here is what you should do: 现在,根据本文档的建议,这是您应该做的:

In config/initializers/predictor.rb , config/initializers/predictor.rb

Predictor.redis = Redis.new(:url => ENV["PREDICTOR_REDIS"])

Or, to improve performance, add hiredis as your driver (you'll need to install the hiredis gem first) 或者,为了提高性能,将hiredis添加为驱动程序(您需要先安装hiredis gem)

Predictor.redis = Redis.new(:url => ENV["PREDICTOR_REDIS"], :driver => :hiredis)

Then, be sure to include include Predictor::Base in all models you want to use it, 然后,确保在要使用它的所有模型中include Predictor::Base

class CourseRecommender
  include Predictor::Base
  ...
end

Here is the code responsible for the error you getting. 是导致错误的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM