[Redis] Setup redis with Rails

  1. Install Gemfile
    gem 'redis'
    gem 'redis-namespace'
  2. Create file config: redis.yml
       host: hdev01
       port: 6479
       db: 0
       namespace: 4travel
  3. Create function for load file config
    def redis_config
      @redis_config ||= YAML.load(File.open(Rails.root.join("config/redis.yml"))).symbolize_keys[Rails.env.to_sym].symbolize_keys
  4. Create namspace redis with function config

    def redis
      @redis ||= Redis::Namespace.new(redis_config[:namespace], :redis => Redis.new(redis_config))
  5. Use redis to set and get data

    #set data
    redis.set(key, value, ex: expiration_time)
    #get data
    redis.keys('*').grep(...) # get all keys and use grep to filter

[Redis] Command in redis

1. Access redis-cli

redis-cli -p <port>

2. Show keys

keys *  // all key
keys "*abc*" // keys contain abc

3. Delete key

// each key
del key1 key2


We have keys:

1) “ab:1”

2) “ab:2”

3) “ab:3”

// multiple key with text ab
EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 ab:*

[Redis] Add 1 more port for Redis

  • Create a new redis .conf file
cp /etc/redis.conf /etc/redis_6479.conf
  • Edit /etc/redis_6479.conf
#modify pidfile
#pidfile /var/run/redis/redis.pid
pidfile /var/run/redis/redis_6479.pid

#modify port
#port 6379
port 6479

#modify logfile
#logfile /var/log/redis/redis.log
logfile /var/log/redis/redis_6479.log
  • Copy init script
cp /etc/init.d/redis /etc/init.d/redis_6479
  • and edit init script
  • Start 1 more redis with port 6479
sudo /etc/init.d/redis_6479 start

# or check status, restart
sudo /etc/init.d/redis_6479 status
sudo /etc/init.d/redis_6479 restart
  • Check port is running of redis:
ps aux |grep redis