Ruby Connection Examples

The redis-rb gem is the recommended client for Redis when using Ruby.

Installation

Install redis-rb at the command prompt if you haven’t yet:

$ gem install redis

Connecting with SSL

Connecting to your instance via SSL requires using a certificate authority. See documentation for certificates and fingerprints for more details.

require 'redis'

begin
  redis = Redis.new(
    :host => '#####.publb.rackspaceclouddb.com',
    :port => 6380,
    :password => 'YOUR_PASSWORD',
    :ssl => :true,
    :ssl_params => {
       :ca_file => 'LOCAL/PATH/TO/rackspace-ca-2016.pem'
    }
  )
  puts redis.info
  client_ping = redis.ping
  if client_ping
    puts 'Connected!'
  else
    raise 'Ping failed'
  end
rescue => e
  puts "Error: #{e}"
end

Connecting without SSL

require 'redis'

begin
  redis = Redis.new(
    :host => '#####.publb.rackspaceclouddb.com',
    :port => 6379,
    :password => 'YOUR_PASSWORD'
  )
  puts redis.info
  client_ping = redis.ping
  if client_ping
    puts 'Connected!'
  else
    raise 'Ping failed'
  end
rescue => e
  puts "Error: #{e}"
end

Creating, Reading, Updating and Deleting Records

require 'redis'

begin
  redis = Redis.new(
    :host => '#####.publb.rackspaceclouddb.com',
    :port => 6379,
    :password => 'YOUR_PASSWORD'
  )
  puts 'Create Record:', redis.set('best_car_ever', 'Tesla Model S')
  puts 'Get Record:', redis.get('best_car_ever')
  puts 'Delete Record:', redis.del('best_car_ever')
  puts 'Get Deleted Record:', redis.get('best_car_ever')
rescue => e
  puts "Error: #{e}"
end

Output from above:

Create Record:
OK
Get Record:
Tesla Model S
Delete Record:
1
Get Deleted Record:

More Information

If you need additional help with redis-rb, here are some useful links:

As always, if you have any questions, please don’t hesitate to reach out to our support team!