What is the best way to use Redis in a Multi-threaded Rails environment? (Puma / Sidekiq)

前端 未结 1 707
半阙折子戏
半阙折子戏 2020-12-14 00:28

I\'m using Redis in my application, both for Sidekiq queues, and for model caching.

What is the best way to have a Redis connection available to my models, consideri

1条回答
  •  失恋的感觉
    2020-12-14 01:19

    You use a separate global connection pool for your application code. Put something like this in your redis.rb initializer:

    require 'connection_pool'
    REDIS = ConnectionPool.new(size: 10) { Redis.new }
    

    Now in your application code anywhere, you can do this:

    REDIS.with do |conn|
      # some redis operations
    end
    

    You'll have up to 10 connections to share amongst your puma/sidekiq workers. This will lead to better performance since, as you correctly note, you won't have all the threads fighting over a single Redis connection.

    All of this is documented here: https://github.com/mperham/sidekiq/wiki/Advanced-Options#connection-pooling

    0 讨论(0)
提交回复
热议问题