Monday, July 11, 2016

Redis + Java = Jedis

"Jedis is a blazingly small and sane Redis java client."

Jedis wiki is here - https://github.com/xetorthio/jedis/wiki

Here's a tutorial: http://www.tutorialspoint.com/redis/redis_java.htm

If you want to download Jedis jar (compiled, not the source zip they offer on their Github page), use this link - http://repo1.maven.org/maven2/redis/clients/jedis/
Go to the folder with the greatest version number (currently 2.8.1, but it'll change) and download jedis-.jar (jedis-2.8.1.jar at the moment).

Don't forget to add this jar to your CLASSPATH both for javac (when you compile your project) and for java (when you run it).

Another option, besides Jedis, is Lettuce - see here for short introductions for both Lettuce and Jedis.

Finally, here's a small example of my own:

package kotodemo.jedis_test;

import java.util.Set;
import redis.clients.jedis.Jedis;

class JedisTest1
{
 public static void main(String[] args)
 {
  // Connecting to Redis server on localhost
  Jedis jedis = new Jedis("localhost", 6100); // Note the non-standard port 6100 I'm using
  // Check whether server is running or not
  System.out.println("Server is running: " + jedis.ping());

  // Get the names of all the keys print them
  Set keys = jedis.keys("*");
  for(String keyStr : keys)
   System.out.println(keyStr);
 }
}

Update: to connect to a non-zero Redis database, use Redis URI to initialize Jedis object, like so:
import java.net.URI;
. . .
Jedis jedis = new Jedis(new URI("redis://localhost:6100/7"));
where 6100 is Redis port I used to test this particular code snippet and 7 is Redis DB I wanted to connect to.

More information on Redis URIs (URLs):

No comments:

Post a Comment