Redis with Ruby
To use Redis with Ruby, you need a Ruby Redis client. The following sections demonstrate the use of redis-rb, a Ruby client library for Redis. Additional Ruby clients for Redis can be found under the Ruby section of the Redis Clients page.
See redis-rb’s README file for installation instructions.
gem to install redis-rb:
gem install redis
Add the following line to your Gemfile:
Connect to Redis
The following code creates a connection to Redis using redis-rb:
require 'redis' redis = Redis.new ( :host => 'hostname', :port => port, :password => 'password')
To adapt this example to your code, replace the following values with your database’s values:
- In line 4, set
:hostto your database’s hostname or IP address
- In line 5, set
:portto your database’s port
- In line 6, set
:passwordto your database’s password
Example code for Redis commands
Once connected to Redis, you can read and write data with Redis command functions.
The following code snippet assigns the value
bar to the Redis key
foo, reads it back, and prints it:
# open a connection to Redis ... redis.set('foo', 'bar'); value = redis.get('foo'); puts value
$ ruby example_redis-rb.rb bar
The redis-rb client does not support SSL connections natively.
For an added security measure, you can secure the connection using stunnel or this redis-rb fork, which includes SSL support.