Tuesday, August 16, 2011

Connect Rails and Redis

These days Redis is getting very popular because of its document style storage and high performance. It is a persistent in-memory key-value store written in C by Salvatore Sanfilippo. Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

When to use Redis :
  • You want to access the data very fast.
  • Your data set is not big and it can fit in available RAM
  • And your data is not very critical if it loose due to any failure 

Install redis:
Download and install from http://redis.io/download

Start Redis
Go to terminal and type :
By default it will run on port 6379

Connecting Redis with Rails 
Once Redis is installed and running follow these steps:
1.) Open gemfile
gem 'redis', '2.1.1'
2.) Then go to your application directory from terminal and execute:
bundle install
3.)Go to following directory /config/initializers/ and create a file redis.rb
4.) Write the following code in redis.rb
$redis = Redis.new(:host => 'localhost', :port => 6379)
By default redis run on 6379, if you are running on different port change this port attribute.

All configuration is completed and now you can use $redis global variable from your rails application.
Checking the connection :
Go to rails console and type following command
=> Redis client v2.1.1 connected to redis://localhost:6379/0 (Redis v2.2.2)

Some Redis Examples
> $redis.set("website","itsallaboutruby")
=> "OK"

1 comment:

  1. awesome post presented by you..your writing style is fabulous and keep update with your blogs Ruby on Rails Online Course Bangalore