redis How to Connect to Redis in Java using Jedis Connecting to Redis


Example

Using a Pool

Most code will want to connect to Redis using a pool of shared connection objects. Connecting to Redis using a pool involves two different code block. At initialization time, your application needs to create the connection pool:

    JedisPoolConfig poolCfg = new JedisPoolConfig();
    poolCfg.setMaxTotal(3);

    pool = new JedisPool(poolCfg, hostname, port, 500, password, false);

The JedisPoolConfig provides options for tuning the pool.

As your application processes it's workload, you will need to get a connection from the shared pool using the following code:

    try (Jedis jedis = pool.getResource()) {

        ...
    }

Best practice is to get the Jedis connection object from the pool within a try-with-resources block.

Without Pools

In some cases, such as a simple application or an integration test, you may not want to deal with shared pools and instead create the Jedis connection object directly. That can be accomplished with the following code:

try (Jedis jedis = new Jedis(hostname, port)) {
    jedis.connect();
    jedis.auth(password);
    jedis.select(db);

    . . .
}

Again, best practice is to create the Jedis client object within a try-with-resources block.