Skip to content

Redis with redis-rb (Ruby)

Uses the redis gem 6.0. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

redis://:secret@redis.example.com:6379/0
redis://:secret@machnosql.example.com:6379/0

The address comes from the environment variable REDIS_URL, so switching to MachNoSQL changes configuration only.

Terminal window
export REDIS_URL='redis://:secret@machnosql.example.com:6379/0'
bundle install
bundle exec ruby app.rb

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.rb
# Cache, counter, session and leaderboard on Redis, unchanged on MachNoSQL.
require "redis"
redis = Redis.new(url: ENV.fetch("REDIS_URL"))
redis.set("cache:home", "<html>...</html>", ex: 60)
puts "cached: #{redis.get("cache:home")} ttl: #{redis.ttl("cache:home")}"
puts "views: #{redis.incr("views:home")}"
redis.hset("session:42", "user", "ada", "cart_items", 3)
puts "session: #{redis.hgetall("session:42")}"
redis.zadd("leaderboard", [[120, "ada"], [95, "linus"], [130, "grace"]])
puts "top: #{redis.zrevrange("leaderboard", 0, 2, with_scores: true)}"
results = redis.multi do |tx|
tx.incr("orders:count")
tx.lpush("orders:recent", "order-1001")
tx.ltrim("orders:recent", 0, 99)
end
puts "pipeline: #{results}"
Gemfile
source "https://rubygems.org"
gem "redis", "~> 6.0"