Created
July 9, 2019 19:34
-
-
Save DevoKun/3681ba98214acae2de8c38092f2193a7 to your computer and use it in GitHub Desktop.
Using Redis with Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'redis' | |
# gem install redis | |
## | |
## Connect to DB | |
## | |
redis = Redis.new(host: "localhost") | |
## | |
## Simple Key/Value Storage | |
## | |
redis.set("a", 1) | |
redis.get("a") | |
## | |
## Sorted Set (aka, a key/value with a weight) | |
## | |
redis.zadd("popular_fruit", 10, "apple") | |
redis.zadd("popular_fruit", 20, "banana") | |
redis.zadd("popular_fruit", 30, "orange") | |
# start at 0, return everything in descending order | |
redis.zrevrange("popular_fruit", 0, -1) | |
# start at 0, return everything in ascending order | |
redis.zrange("popular_fruit", 0, -1) | |
# start at 0, return 1 item | |
redis.zrevrange("popular_fruit", 0, 0) | |
# start at 0, return 2 items | |
redis.zrevrange("popular_fruit", 0, 1) | |
## | |
## Use colons to namespace the data | |
## | |
redis.set("fruit:red", "apple") | |
redis.set("fruit:yellow", "banana") | |
## | |
## Query ALL keys in database | |
## | |
redis.keys() | |
# | |
# scan is a cursor based iterator. | |
# This means that at every call of the command, | |
# the server returns an updated cursor that the user needs to use as the cursor argument in the next call. | |
# An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0. | |
# | |
i = 0 | |
loop do | |
results = redis.scan(i) | |
i = results.first.to_i | |
results.last.each do |key| | |
puts " * " + key.to_s | |
end ## each | |
break if i == 0 | |
end | |
## | |
## Data persistence | |
## | |
## Redis only writes data to disk _(dump.rdb)_ when the server is stopped. | |
## Or under these conditions: | |
## * after 15 min, if 1 or more keys changed | |
## * after 5 min, if 10 or more keys changed | |
## * after 1 min, if 10,000 or more keys changed | |
## | |
## To make Redis save to disk every second, set: `appendonly yes` | |
## | |
## | |
## Using Redis as a cache in Rails | |
## | |
# config/environments/production.rb | |
Rails.application.configure do | |
config.cache_store = :redis_cache_store, { url: "redis://localhost:6379/0" } | |
end | |
Rails.cache.write("a", 1) | |
Rails.cache.read("a") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment