Skip to content

Instantly share code, notes, and snippets.

@solutelabs-savan
Last active May 11, 2016 09:15
Show Gist options
  • Save solutelabs-savan/974280944d85d178534fe13f587adf4a to your computer and use it in GitHub Desktop.
Save solutelabs-savan/974280944d85d178534fe13f587adf4a to your computer and use it in GitHub Desktop.
Work with 2R combinations - Rails & Redis
Install Redis on ubuntu first
1) Add PPA
$ sudo add-apt-repository ppa:chris-lea/redis-server
Press ENTER to accept the repository.
2) Run the following command to update our packages:
$ sudo apt-get update
3) Install the Redis server:
$ sudo apt-get install redis-server
4) Check that Redis is up and running:
$ redis-benchmark -q -n 1000 -c 10 -P 5
Configure Redis Master
5) Open /etc/redis/redis.conf with your favorite text editor:
$ sudo nano /etc/redis/redis.conf
Edit the following lines.
6) Set a sensible value to the keepalive timer for TCP:
>> tcp-keepalive 60
7) Make the server accessible to anyone on the web by commenting out this line:
>> #bind 127.0.0.1
NOTE : This step #7 is only for the production enviornment
8) Given the nature of Redis, and its very high speeds, an attacker may brute force the password without many issues. That is why we recommend uncommenting the requirepass line and adding a complex password (or a complex passphrase, preferably):
>> requirepass <your_redis_master_password>
9) Save your changes.
We are done with setup
10) Restart the Redis service to reload our configuration changes:
$ sudo service redis-server restart
11) Now we have to start redis server to allow application to store values.
$ redis-server
NOTE : Start redis server in background for production env.
We will connect rails application to redis, work with redis I would suggest you to run application using thin / puma server.
Follow the steps
1) Add gems in Gemfile
gem 'redis'
gem 'redis-namespace'
gem 'redis-rails'
gem 'redis-rack-cache'
2) Add line in /config/initializers/session_store.rb
Rails.application.config.session_store :redis_store, servers: { host: "localhost",
port: 6379,
db: 0,
password: "redis-master-password-which-we-add-in-above-steps",
namespace: "session"
},
expires_in: 60.minutes
3) Add line in /config/application.rb
config.cache_store = :redis_store, { host: "localhost",
port: 6379,
db: 0,
password: "redis-master-password-which-we-add-in-above-steps",
namespace: "cache",
expires_in: 60.minutes }
4) Create a file redis.rb inside /config/initializers/ and add this line there
$redis = Redis.new(:host => 'localhost', :port => 6379)
We may now issue Redis commands directly to the $redis global variable. Let’s test it out by opening a RAILS CONSOLE (rails c) and executing the following commands:
> $redis.set("user_name", "savan.raval")
=> "OK"
> $redis.get("user_name")
=> "savan.raval"
> $redis.get("user_id")
=> nil
> $redis.del("user_name")
=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment