'Rails redis cache connection (pool) proper usage in threads

Disclaimer: I really must not be Googling my question properly because this does seem like a basic question.

Basic question: I want to how how to proper use Rails.cache in threads when I do and do not have a connection pool. This applies to Redis, Memcache or anything else that requires a connection.

No ConnectionPool

I believe: If I spawn a thread, I believe that I must manually tell the cache to reconnect to Redis or else I will receive the error Tried to use a connection from a child process without reconnecting. You need to reconnect to Redis after forking or set :inherit_socket to true.

  1. How do I reconnect? There is no Rails.cache.reconnect or Rails.cache.redis.reconnect method. The only thing I can find is Rails.cache.redis.disconnect!

With ConnectionPool

The interface to Rails.cache.redis changes because it's now an instance of ConnectionPool instead of an instance of Redis.

I believe: If I spawn a thread, I believe that I must call checkout a connection and then check it back in? connection = Rails.cache.redis.checkout and then Rails.cache.redis.checkin(connection)? (I think in Rails 7 they introduced with_connection which takes a block and does the checkout and checkin for you).

  1. Is this really the kind of threading maintenance work that I have to do manually? Spawn thread, worry about my cache connection pool, end thread? Or is this handled automatically when using a connection pool? What if my connection pool is just 1 connection? The DB connection pool doesn't seem to need this, eh?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source