LoginSignup
16
14

More than 5 years have passed since last update.

railsでコネクションプールを使ってredisに接続する

Posted at

railsはActiveRecordがデータベース周りの処理をすべて面倒見てくれて便利です。けれどもRDMS以外を使うと、少し自分でやらないといけないことが増えます。redisを使うときにコネクションプールを利用する方法のメモです。

gemファイル

redisのクライアントはredis、コネクションプールはconnection_poolを使います。

gem 'redis'
gem 'connection_pool'

redisの設定ファイル

redisで情報を保存する設定ファイルを用意します。設定ファイルはconfig/redis.ymlで、次のように記述します。

default: &default
  host: localhost
  port: 6379

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default
  host: redis-server

redisのインスタンス化

config/initializers/redis.rb で初期化します。

# Load the redis.yml configuration file
redis_config = YAML.load_file(Rails.root + 'config/redis.yml')[Rails.env]

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

最初にredis.ymlを読み込んで、稼働中の環境のredisの設定を読み込んでいます。
次にRedis.currentにコネクションプールのオブジェクトをセットしています。これだけです。

redisの利用

最後にredisの利用方法です。コントローラなどから次のように使います。

Redis.current.with do |redis|
  redis.sadd 'foo', 1
end

本当にコネクションプールが使われているかどうかは未確認ですが、ライブラリを信用しましょう。

おわりに

簡単にコネクションプールを利用できるようになりました。次回はActive Job + sidekiq + redisのメモです。

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14