Redis Java

Make Redis Java super easy with Redis Labs

Redis Labs’ products and services enable running Redis datasets in a highly available and auto-scalable manner, with predictable top performance.

The Redise Pack lets you install an enterprise grade Redis cluster in your environment of choice, whether an on-premises data-center or your preferred cloud platform. It gives you full control of your data and configuration – no clustering or sharding knowledge required!

Redise Cloud is a fully-managed cloud service for hosting and running Redis dataset without dealing with nodes, clusters, failure recovery or performance stabilization. Our technology does all that in a fully automated manner. Redise Cloud is available on all popular clouds and platforms-as-a-service.

Using Redis with Java

In order to use Redis with Java you will need a Java Redis client. In following sections, we will demonstrate the use of lettuce and Jedis. Additional Java clients for Redis can be found under the Java section of the Redis Clients page.

Lettuce

Lettuce is a scalable thread-safe Redis client providing both synchronous and asynchronous connections.

Installing lettuce

Lettuce’s installation instructions are given in the “Binaries/Download” section of its README file. Use lettuce by declaring the following Maven dependency:

<dependency>
    <groupId>biz.paluch.redis</groupId>
    <artifactId>lettuce</artifactId>
    <version>3.2.Final</version>
</dependency>

You can also download the latest lettuce release from the GitHub repository: https://github.com/mp911de/lettuce/wiki/Download

Opening a Connection to Redis using lettuce

The following code creates a connection to Redis using lettuce:

import com.lambdaworks.redis.*;

public class ConnectToRedis {

  public static void main(String[] args) {
    RedisClient redisClient = new RedisClient(
      RedisURI.create("redis://password@host:port"));
    RedisConnection<String, String> connection = redisClient.connect();

    System.out.println("Connected to Redis");

    connection.close();
    redisClient.shutdown();
  }
}

To adapt this example to your code, make sure that you replace the following values with those of your database:

  • In line 7, the URI contains the password. The argument should be your database’s password. Remove password@ to connect without authentication
  • In line 7, the URI contains the host. The argument should be your database’s host.
  • In line 7, the URI contains the port. The argument should be your database’s port.

lettuce is thread-safe, and the same lettuce connection can be used from different threads. Using multiple connections is also possible.

If you’re using Spring, use the following plain Spring XML to create a lettuce instance:

<bean id="RedisClient" class="com.lambdaworks.redis.support.RedisClientFactoryBean">
    <property name="uri" value="redis://host:port"/>
</bean>

and use it then within your managed beans as follows:

import com.lambdaworks.redis.*;
import org.springframework.beans.factory.annotation.Autowired;

public class MySpringBean {

    private RedisClient redisClient;

    @Autowired
    public void setRedisClient(RedisClient redisClient) {
        this.redisClient = redisClient;
    }

    public String ping() {

        RedisConnection<String, String> connection = redisClient.connect();
        String result = connection.ping();
        connection.close();
        return result;
    }
}

Once your standalone-application exits, remember to shutdown lettuce by using the shutdown method:

client.shutdown();

If you are using Spring and CDI, the frameworks will manage the resources for you and you do not have to close the client using the shutdown method.

Using SSL and lettuce

For an added security measure, you can secure the connection using SSL connections. lettuce supports SSL connections natively.

import com.lambdaworks.redis.*;

public class ConnectToRedisSSL {

    public static void main(String[] args) {
        RedisClient redisClient = new RedisClient(
            RedisURI.create("rediss://password@host:port"));
        RedisConnection<String, String> connection = redisClient.connect();
        System.out.println("Connected to Redis using SSL");

        connection.close();
        redisClient.shutdown();
    }
}

Note: Depending on your server’s SSL configuration, you may need to install certificates in your local JVM using the keytool utility.

Reading and Writing Data with lettuce

Once connected to Redis, you can start reading and writing data. The following code snippet writes the value bar to the Redis key foo, reads it back, and prints it:

// open a connection to Redis
...

connection.set("foo", "bar");
String value = connection.get("foo");
System.out.println(value);

The output of the above code should be:

$ java ReadWriteExample
Connected to Redis
bar

Jedis

Jedis is a blazingly small and sane Redis Java client.

Installing Jedis

Jedis’ installation instructions are given in the “How do I Use it?” section of its README file. Use Jedis by declaring the following Maven dependency:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.6.2</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

You can also download the latest Jedis release from the GitHub repository. To build it, extract the source and run the following command:

$ cd jedis
~/jedis$ make package

Opening a Connection to Redis Using Jedis

The following snippet demonstrates creating a connection to Redis using Jedis:

import redis.clients.jedis.Jedis;

public class JedisExample {

  public static void main(String[] args) throws Exception {
    Jedis jedis = new Jedis("hostname.redislabs.com", 6379);
    jedis.auth("password")
    System.out.println("Connected to Redis");
  }
}

To adapt this example to your code, make sure that you replace the following values with those of your database:

  • In line 6, the first argument to Jedis should be your database’s hostname or IP address
  • In line 6, the second argument to Jedis should be your database’s port
  • In line 7, the argument to auth should be your database’s password

Connection Pooling with Jedis

Jedis isn’t thread-safe and the same Jedis instance shouldn’t be used from different threads. To overcome the overhead of multiple Jedis instances and connection maintenance, use JedisPool. To use JedisPool you’ll have to have Apache Commons Pool 2.3 available – download it from here or add the following Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.3</version>
</dependency>

The following snippet demonstrates how to instantiate a pool of connections using JedisPool:

JedisPool pool = new JedisPool(new JedisPoolConfig(), "hostname.redislabs.com", 6379, Protocol.DEFAULT_TIMEOUT, "password");

If you’re using Spring, use the following Plain Spring XML to create JedisPool:

<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig" />
        <constructor-arg index="1" value="hostname.redislabs.com" />
        <constructor-arg index="2" value="6379" />
        <constructor-arg index="3" value="Protocol.DEFAULT_TIMEOUT" />
        <constructor-arg index="4" value="password" />
    </bean>

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" >
</bean>

JedisPool is thread-safe and can be stored in a static variable and shared among threads. Getting a Jedis instance from the JedisPool is demonstrated by the following snippet:

Jedis redis = null;
    try
    {
        redis = redisPool.getResource();
        return redis.get(keyName);
    }
    catch (JedisConnectionException e)
    {
        if (redis != null)
        {
            redisPool.returnBrokenResource(redis);
            redis = null;
        }
        throw e;
    }
    finally
    {
        if (redis != null)
        {
            redisPool.returnResource(redis);
        }
    }
}

Once your application exits, remember to dispose of the JedisPool by using the destroy method:

pool.destroy();

Using SSL and Jedis

Beginning with versions 2.8.2 and 2.9.0, Jedis supports SSL. Creating a connection over SSL is done by using the rediss:// scheme in the server’s URI, for example:

Jedis jedis = new Jedis(URI.create(“rediss://hostname:port”));
 

Note: Depending on your server’s SSL configuration, you may need to install certificates in your local JVM using the keytool utility.

Reading and Writing Data with Jedis

Once connected to Redis, you can start writing and reading data. The following code snippet demonstrates writing the value bar to the Redis key foo and then reading it back:

// open a connection to Redis
...

jedis.set("foo", "bar");
String value = jedis.get("foo");
System.out.println(value);

The output of the above code should be:

$ java JedisExample
Connected to Redis
bar

For more information on using Redis Labs’ products and services with Java please see the Howto page.