Redis To Go
Table of Contents
Redis is a key-value store similar to memcached, but non-volatile; it supports lists, hashes, sets, and ordered sets.
Using Redis from Ruby
Gem Setup
The redis-rb client is the easiest way to access Redis from Ruby. Install redis-rb with sudo gem install redis.
Using from Rails
For Rails 2.3.3 and higher, update the config/environment.rb to include the redis gem.
config.gem 'redis'
If using Rails 3, update the Gemfile:
gem 'redis'
Setup the Redis connection information for development in config/environments/development.rb
ENV["REDISTOGO_URL"] = 'redis://username:password@my.host:6789'
Configure Redis in config/initializers/redis.rb
uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
Test that it works in the console.
$ rails console
>> REDIS.set("foo", "bar")
"OK"
>> REDIS.get("foo")
"bar"
Using from Sinatra
In the configure block include:
configure do
require 'redis'
uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
end
Test that it works in the console.
$ irb -r myapp.rb
>> REDIS.set("foo", "bar")
"OK"
>> REDIS.get("foo")
"bar"
Using Redis from Java
There are several Java libraries available for connecting to Redis, including Jedis and JRedis. This guide will shows to use Jedis from both a generic Java application and a Spring configured application.
Add Jedis to Dependencies
Include the Jedis library in your application by adding the following dependency to pom.xml:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.0.0</version>
</dependency>
Use Redis in your application
The connection information for the Redis Service provisioned by Redis To Go is stored as a URL in the REDISTOGO_URL config var. You can create a Jedis connection pool from this URL string with the following code snippet:
try {
URI redisURI = new URI(System.getenv("REDISTOGO_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. Handle exception
}
Now you can use this pool to perform Redis operations. For example:
Jedis jedis = pool.getResource();
try {
/// ... do stuff here ... for example
jedis.set("foo", "bar");
String foobar = jedis.get("foo");
jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike");
Set<String> sose = jedis.zrange("sose", 0, -1);
} finally {
/// ... it's important to return the Jedis instance to the pool once you've finished using it
pool.returnResource(jedis);
}
(example taken directly from Jedis docs).
Using Redis with Spring
Use the following Java Configuration class to set up a JedisPool instance as a singleton Spring bean:
@Configuration
public class SpringConfig {
@Bean
public JedisPool getJedisPool() {
try {
URI redisURI = new URI(System.getenv("REDISTOGO_URL"));
return new JedisPool(new JedisPoolConfig(),
redisURI.getHost(),
redisURI.getPort(),
Protocol.DEFAULT_TIMEOUT,
redisURI.getUserInfo().split(":",2)[1]);
} catch (URISyntaxException e) {
throw new RuntimeException("Redis couldn't be configured from URL in REDISTOGO_URL env var:"+
System.getenv("REDISTOGO_URL"));
}
}
}
or the following XML configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:property-placeholder/>
<bean id="jedisURI" class="java.net.URI">
<constructor-arg value="${REDISTOGO_URL}"/>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"/>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="#{ @jedisURI.getHost() }"/>
<constructor-arg index="2" value="#{ @jedisURI.getPort() }"/>
<constructor-arg index="3" value="#{ T(redis.clients.jedis.Protocol).DEFAULT_TIMEOUT }"/>
<constructor-arg index="4" value="#{ @jedisURI.getUserInfo().split(':',2)[1] }"/>
</bean>
</beans>
Sample code
To see a complete, working example, check out the sample code in github. The readme explains more about the example.
Using Redis from Python
The redis-py client is the easiest way to access Redis from Python. Install redis-py with pip install redis.
Using from Python
import os, urlparse
if os.environ.has_key('REDIS_TO_GO'):
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(os.environ['REDIS_TO_GO'])
REDIS = redis.Redis(host=url.hostname, port=url.port, db=0, password=url.password)
Using as a Django Cache
import os, urlparse
if os.environ.has_key('REDIS_TO_GO'):
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(os.environ['REDIS_TO_GO'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': '%s:%s' % (url.hostname, url.port),
'OPTIONS': {
'DB': 0,
'PASSWORD': url.password,
'PARSER_CLASS': 'redis.connection.HiredisParser'
},
},
}
Deploying to Heroku
To use Redis To Go on Heroku, install the redistogo add-on:
$ heroku addons:add redistogo
Test that it works from the Heroku console:
$ heroku console
>> REDIS.set("answer", 42)
"OK"
>> REDIS.get("answer")
42