14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails でサクッと Redis を Master/Slave 構成にする

Posted at

このようなgemもありますが
https://github.com/oggy/redis_master_slave

config/initializers に数行加えるだけで振り分けが可能です。
コネクションプール等を使ってると不具合があるかもしれません。

config/initializers/redis.rb
class Redis
  class Client
    def call(command, &block)
      master_host = MASTER_HOST_URI
      slave_host  = SLAVE_HOST_URI

      # Slave に向けたいお好きなコマンドを登録
      slave_commands = [:get, :hget, :hgetall] 

      disconnect
      @options[:host] = if slave_commands.include?(command[0])
        slave_host 
      else
        master_host
      end
      connect

      reply = process([command]) { read }
      raise reply if reply.is_a?(CommandError)

      if block
        block.call(reply)
      else
        reply
      end
    end
  end
end
14
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
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?