Skip to content

Commit

Permalink
split article from readme. Add procfile.
Browse files Browse the repository at this point in the history
  • Loading branch information
jsimone committed Nov 22, 2011
1 parent 4e0fcda commit ad58754
Show file tree
Hide file tree
Showing 5 changed files with 165 additions and 123 deletions.
103 changes: 103 additions & 0 deletions ARTICLE.md
@@ -0,0 +1,103 @@
## Using Redis from Java

There are several Java libraries available for connecting to Redis, including [Jedis](https://github.com/xetorthio/jedis) and [JRedis](http://code.google.com/p/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:

:::java
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:

:::java
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

Using the following Java Configuration class to set up a `JedisPool` instance as a singleton Spring bean:

:::java
@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
<?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](https://github.com/heroku/devcenter-redis-java). The [readme](https://github.com/heroku/devcenter-redis-java/blob/master/README.md) explains more about the example.
2 changes: 2 additions & 0 deletions Procfile
@@ -0,0 +1,2 @@
sample: sh target/bin/sample
springsample: sh target/bin/spring-sample
137 changes: 16 additions & 121 deletions README.md
@@ -1,106 +1,8 @@
## Using Redis from Java

There are several Java libraries available for connecting to Redis, including [Jedis](https://github.com/xetorthio/jedis) and [JRedis](http://code.google.com/p/jredis/). This guide will show how to use Jedis from both a generic Java application and a Spring configured application.
This is an example of using Jedis to connecto to the Redis To Go service from both a generic Java application and a Spring configured application on Heroku. Read more about how to use Redis To Go in the [add-on article](http://devcenter.heroku.com/articles/redistogo).

### 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:

:::java
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:

:::java
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

Using the following Java Configuration class to set up a `JedisPool` instance as a singleton Spring bean:

:::java
@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
<?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](https://github.com/heroku/devcenter-redis-java).
# Using The Sample Code

Clone the repo with:

Expand All @@ -123,27 +25,20 @@ Build the sample:
Run it with foreman:

$ foreman start
22:21:21 web.1 | started with pid 46300
22:21:21 web.1 | Nov 20, 2011 10:21:21 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
22:21:21 web.1 | INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@182d9c06: startup date [Sun Nov 20 22:21:21 PST 2011]; root of context hierarchy
22:21:21 web.1 | Nov 20, 2011 10:21:21 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
22:21:21 web.1 | INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4b0ab323: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springConfig,getJedisPool]; root of factory hierarchy
22:21:21 web.1 | Setting up new RedisPool for connection redis://:@localhost:6379
22:21:21 web.1 | 2011-11-20 22:21:21.707:INFO:oejs.Server:jetty-7.5.4.v20111024
22:21:21 web.1 | 2011-11-20 22:21:21.810:INFO:oejsh.ContextHandler:started o.e.j.s.ServletContextHandler{/,null}
22:21:21 web.1 | 2011-11-20 22:21:21.838:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:5000 STARTING

Test it with curl. Set a new value:

:::term
$ curl http://localhost:5000/mykey -d "value=myvalue"
/mykey = myvalue

and get the value

:::term
$ curl http://localhost:5000/mykey
/mykey = myvalue
22:31:48 sample.1 | started with pid 74251
22:31:48 springsample.1 | started with pid 74252
22:31:48 sample.1 | Setting up new RedisPool for connection redis://redistogo:9451749016f2bd2780a19abe20d343b8@viperfish.redistogo.com:9411/
22:31:48 springsample.1 | Nov 21, 2011 10:31:48 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
22:31:48 springsample.1 | INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@95c083: startup date [Mon Nov 21 22:31:48 PST 2011]; root of context hierarchy
22:31:48 springsample.1 | Nov 21, 2011 10:31:48 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
22:31:48 springsample.1 | INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d8d9850: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springConfig,getJedisPool]; root of factory hierarchy
22:31:48 springsample.1 | Setting up new RedisPool for connection redis://redistogo:9451749016f2bd2780a19abe20d343b8@viperfish.redistogo.com:9411/
22:31:49 springsample.1 | Value set into Redis is: testValueSpring
22:31:49 sample.1 | Value set into Redis is: testValue
22:31:49 springsample.1 | Value retrieved from Redis is: testValueSpring
22:31:49 sample.1 | Value retrieved from Redis is: testValue
22:31:49 springsample.1 | process terminated
22:31:49 system | sending SIGTERM to all processes


You can switch between the Java and XML based configuration by commenting out one of the two lines in `Main.java` in the `spring` sub-package:
Expand Down
42 changes: 42 additions & 0 deletions pom.xml
Expand Up @@ -27,4 +27,46 @@
<version>2.2.2</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>

<!-- The maven app assembler plugin will generate a script that sets up the classpath and runs your project -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.1.1</version>
<configuration>
<assembleDirectory>target</assembleDirectory>
<programs>
<program>
<mainClass>com.heroku.devcenter.Main</mainClass>
<name>sample</name>
</program>
<program>
<mainClass>com.heroku.devcenter.spring.Main</mainClass>
<name>spring-sample</name>
</program>
</programs>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4 changes: 2 additions & 2 deletions src/main/java/com/heroku/devcenter/spring/Main.java
Expand Up @@ -17,10 +17,10 @@ public static void main(String[] args) {
try {
String testValue = "testValueSpring";

jedis.set("testKey", testValue);
jedis.set("testKeySpring", testValue);
System.out.println("Value set into Redis is: " + testValue);

System.out.println("Value retrieved from Redis is: " + jedis.get("testKey"));
System.out.println("Value retrieved from Redis is: " + jedis.get("testKeySpring"));
} finally {
pool.returnResource(jedis);
}
Expand Down

0 comments on commit ad58754

Please sign in to comment.