[Awesome Ruby Gem] Use redis_hash_store gem to easily use Redis hashes for caching
redis_hash_store
RedisHashStore extends ActiveSupport’s RedisCacheStore - https://github.com/rails/rails/blob/master/activesupport/lib/active_support/cache/redis_cache_store.rb to provide the ability to easily use Redis hashes for caching.
We decided to create this gem because:
-
Previously using #delete_matched - https://apidock.com/rails/ActiveSupport/Cache/Store/delete_matched which can have many performance issues at scale (See this similar issue at GitLab - https://gitlab.com/gitlab-org/gitlab/-/issues/201808).
-
#deleted_matched
doesn’t delete values from all the nodes in a Redis cluster.
Installation
You can install it as a gem:
1 | gem install amazing_print |
or add it into a Gemfile (Bundler):
1 | # redis_hash_store |
Then, run bundle install
.
1 | bundle install |
Configuration
1 | # config/production(development|test|staging|preview).rb |
Usages
This gem simply adds new functionality to RedisCacheStore, so all existing logic in that class is not affected.
Here is a list of available methods:
1 | #write_hash_value |
Examples
Let’s imagine we need to store amount of Services for City.
#write_hash_value
1 | city = "Riyadh" |
#read_hash_value
Now it’s accessible by:
1 | Rails.cache.read_hash_value("#{city} counters", coffee_shop_type) |
Looks pretty easy, right? Maybe you’re thinking: “What the difference?”
You can access all records under the “#{city} counters” hash
1 | Rails.cache.read_hash("#{city} counters") |
#fetch_hash_value
1 | You can fetch needed value under "#{city} counters" |
References
[1] GitHub - mrsool/redis_hash_store - https://github.com/mrsool/redis_hash_store
[3] - https://engineering.mrsool.co/using-redis-hashes-for-caching-in-ruby-on-rails-6dc53df293da