Install Redis

1. If you don't already have a Redis Server, you need to install one.

2. For MacOS, install via brew:

$ brew update
$ brew install redis
$ brew services start redis

3. For Ubuntu, install by:

$ sudo apt-get install redis-server

4.Check your Redis Server is started.

$ ps aux | grep redis

You should see something like this:

/usr/local/opt/redis/bin/redis-server 127.0.0.1:6379

5. To change configuration, the config file is located at:

(MacOS) /usr/local/etc/redis.conf
(Ubuntu) /etc/redis/redis.conf

Configuring Redis in Rails

1. Add the redis gem for Rails.

gem 'redis-rails'

2. Install the gem.

$ bundle install

3. Set Redis as your cache store in application.rb

config.cache_store = :redis_store, {
  host: "127.0.0.1",
  port: 6379,
  namespace: "my_cache"
}

4. Create a Redis instance via initializer. (E.g. config/initializers/redis.rb)

$redis = Redis.new

Using Redis

1. Write value to a key:

$redis.set('my_key', 'my value')

2. Read value from a key:

$redis.get('my_key')

nil is returned if key does not exists.

3. Check key exists:

$redis.exists('my_key')
> true

4. Delete a key:

$redis.del('my_key')

5. Delete all keys:

$redis.flushall

6. Set multiple keys in one call:

$redis.mset('my_key_1', 'my_value_1', 'my_key_2', 'my_value_2')

7. Get multiple keys in one call:

@value = $redis.mget('my_key_1', 'my_key_2')
> ["my_value_1", "my_value_2"]

8. Use as increment counter:

$redis.set('my_key', 1)
$redis.incr('my_key')
@value = $redis.get('my_key')
> 2

$redis.set('my_key', 1)
$redis.incrby('my_key', 10)
@value = $redis.get('my_key')
> 11

Redis CLI

1. You can access Redis CLI tool for debugging. Type the command below in your terminal to enter CLI mode.

$ redis-cli

2. To check a value, use the GET command. E.g.

127.0.0.1:6379> GET my_key
"my value"

3. Full list of available commands can be found here.