Skip to content

Instantly share code, notes, and snippets.

@kehati
Forked from Yiftach/gist:3489087
Created August 28, 2012 12:12
Show Gist options
  • Save kehati/3497582 to your computer and use it in GitHub Desktop.
Save kehati/3497582 to your computer and use it in GitHub Desktop.

Redis-Cloud is a fully-automated service for hosting your Redis dataset, providing:

  • Infinite-scalability: supports all Redis commands at any dataset size
  • Reliability: auto-failover with absolutely no data loss. Enhanced data persistence and backup options
  • Performance: no matter how much memory you use, you will always get the highest throughput and lowest latency like if you were running on the strongest EC2 instances
  • Fully managed - completely hassle free

You can quickly and easily get your apps up and running with Redis-Cloud through the Redis-Cloud add-on for Heroku, just tell us how much memory you need and get started instantly with your first database. You can then add as many as possible dedicated databases, increase or decrease your memory capacity as needed and without affecting your existing data.

Getting started

Start by installing the add-on:

:::term
$ heroku addons:add rediscloud:plan_name

Valid values for plan_name values can be found here. For example:

:::term
$ heroku addons:add rediscloud:20MB 
$ heroku addons:add rediscloud:1GB
... etc ...

Once Redis-Cloud has been added, you will notice a REDISCLOUD_URL variable in your heroku config containing the username, password, hostname and port of your first Redis-Cloud database.

:::term
$ heroku config:get REDISCLOUD_URL
http://username:password@hostname:port

Next, setup your app to start using the Redis-Cloud add-on. In the following sections we have documented the interfaces with several languages and frameworks supported by Heroku.

Note: as database provisioning is carried out asynchronously, please wait until the creation and initialization of the database complete. This process shouldn't take more than 60 seconds

Using Redis from Ruby

The redis-rb is a very stable and mature redis client and the easiest way to access Redis from Ruby.

Install redis-rb:

:::term
sudo gem install redis

Configuring Redis from Rails

For Rails 2.3.3 and higher, update the config/environment.rb to include the redis gem:

:::ruby
config.gem 'redis' 

For Rails 3, update the Gemfile:

:::ruby
gem 'redis'  

Setup the Redis connection in config/environments/development.rb:

:::ruby
ENV["REDISCLOUD_URL"] = 'redis://username:password@hostname:port' 

Configure Redis in config/initializers/redis.rb:

:::ruby
uri = URI.parse(ENV["REDISCLOUD_URL"])
redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)

Configuring Redis on Sinatra

In the configure block include:

:::ruby
configure do
	require 'redis'
	uri = URI.parse(ENV["REDISCLOUD_URL"])
	REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
end

Testing (Ruby)

The Redis class exports methods that are named identical to the commands they execute. For instance, the SET and GET commands can be called like this:

:::ruby
redis.set("foo", "bar")
# => "OK"
redis.get("foo")
# => "bar"

Using Redis from Java

Jedis is a blazingly small, sane and easy to use Redis java client. You can download the latest build from github or use it as a maven dependency:

:::java
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.0.0</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>

Configure connection for your Redis-Cloud service using REDISCLOUD_URLconfig vars and the following code snippet:

:::java
try { 
		URI redisUri = new URI(System.getenv("REDISCLOUD_URL"));
		JedisPool pool = new JedisPool(new JedisPoolConfig(),
	    		redisUri.getHost(),
	    		redisUri.getPort(),
	    		Protocol.DEFAULT_TIMEOUT,
	    		redisUri.getUserInfo().split(":",2)[1]);
} catch (URISyntaxException e) {
   	    // URI couldn't be parsed.		   
} 

Testing (Java)

:::java
Jedis jedis = pool.getResource();
jedis.set("foo", "bar");
String value = jedis.get("foo");
// return the instance to the pool when you're done
pool.returnResource(jedis);

(example taken from Jedis docs).

Using Redis from Python

redis-py is a mature and supported Redis client and currently is the way to go for Python.

Install it with:

:::term
sudo pip install redis

And you are ready to get started:

:::python
import os
import urlparse
import redis
url = urlparse.urlparse(os.environ.get('REDISCLOUD_URL', 'redis://localhost'))
r = redis.Redis(host=url.hostname, port=url.port, password=url.password)

Now you can use your Redis:

:::python
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
'bar'

django-redis-cache is a Redis cache backend for Django.

Install django-redis-cache:

:::term
pip install django-redis-cache

Next, configure your CACHES in the settings.py file:

:::python
import os
import urlparse
redis_url = urlparse.urlparse(os.environ.get('REDISCLOUD_URL', 'http://localhost'))
CACHES = {
	'default': {
	'BACKEND': 'redis_cache.RedisCache',
	'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port),
	'OPTIONS': {
        'PASSWORD': redis_url.password,
		'DB': 0,
    }
  }
}

Now you can use your cache:

:::python
from django.core.cache import cache
cache.set("foo", "bar")
print cache.get("foo")

Using Redis from PHP

Predis is a flexible and feature-complete PHP (>= 5.3) client library for the Redis key-value store.

Instructions for installing the Predis library can be found here.

Loading the library to your project is now straightforward::

:::javascript
<?php
// prepend a base path if Predis is not present in your "include_path".
require 'Predis/Autoloader.php';
Predis\Autoloader::register();

Now you can connect to a Redis instance:

:::javascript
$redis = new Predis\Client(array(
	'host' => parse_url($_ENV['REDISCLOUD_URL'], PHP_URL_HOST), 
	'port' => parse_url($_ENV['REDISCLOUD_URL'], PHP_URL_PORT),
	'password' => parse_url($_ENV['REDISCLOUD_URL'], PHP_URL_PASS), 
));

And simply start using it:

:::javascript
$redis->set('foo', 'bar');
$value = $redis->get('foo');

Using Redis from Node.js

node_redis is a complete Redis client for node.js. It supports all Redis commands, including many recently added commands like EVAL from experimental Redis server branches.

You can install it with:

:::term
npm install redis

Now, instantiate a Redis client:

:::javascript
var redis = require('redis');
var url = require('url');
var redisURL = url.parse(process.env.REDISCLOUD_URL);
var client = redis.createClient(redisURL.port, redisURL.hostname, {no_ready_check: true});
client.auth(redisURL.auth.split(":")[1]);

And you can start using it:

:::javascript
client.set('foo', 'bar');
client.get('foo', function (err, reply) {
    console.log(reply.toString()); // Will print `bar`
});

Analytics Dashboard

Our analytics dashboard is a great tool for assesing your redis usage. Here is a screenshot of the dashboard:

Dashboard

To access your Redis analytics dashboard run:

:::term
heroku addons:open rediscloud

And find your dashboard under the MY REDIS DBS menu.

Alternatively, you can access your Redis dashboard by running:

:::term
heroku addons:open rediscloud

Or open Redis Cloud from your application at heroku.com.

Migrating between plans

Plan migrations are easy and instant. You can use the 'heroku addons:upgrade' command to migrate to a new plan:

:::term
$ heroku addons:upgrade rediscloud:10GB

A list of all Redis Cloud plans is available here.

Removing the add-on

Redis Cloud can be removed via the CLI.

This will destroy all associated data and cannot be undone!
:::term
$ heroku addons:remove rediscloud

Support

All Redis Cloud support and runtime issues should be submitted via on of the Heroku Support channels. Any non-support related issues or product feedback is welcome at info@garantiadata.com.

Additional resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment