使用Rails时,像database.yml那样从环境变量中读取Redis的配置

概述

在Rails的database.yml文件中,可以从环境变量中获取配置值,如果无法获取到,则可以使用默认值。这种方法也可以应用在Redis的配置文件中。听说年轻的时候想实现这个功能,但是不知道怎么做,所以决定写下来。

环境

6.0.3版本的Rails

Redis的配置文件

配置文件是 config/redis.yml。

default: &default
  host: <%= ENV.fetch('SESSION_DB_HOST') { 'session_db' } %>
  port: <%= ENV.fetch('SESSION_DB_PORT') { 6379 } %>

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

我正在设置host和port与database.yml相同的方式,如果环境变量存在,我会从环境变量中获取并设置它们;如果环境变量不存在,我会设置为指定的默认值。

Redis 的初始化

在 config/initializers/redis.rb 文件中初始化 Redis。

path = Rails.root + 'config/redis.yml'
yaml = Pathname.new path if path

config =
  if yaml && yaml.exist?
    YAML.load(ERB.new(yaml.read).result)[Rails.env] || {}
  else
    raise "Could not load redis configuration. No such file - #{path}"
  end

Redis.current = ConnectionPool.new(size: 10, timeout: 5) do
  Redis.new(
    host: config['host'],
    port: config['port']
  )
end

在 YAML.load(ERB.new(yaml.read).result)[Rails.env] 这个位置,我们使用 ERB 类来处理已加载的 redis.yml,并将其作为 eRuby 脚本进行处理。

请参考