Redis – Installing and using it in Java on windows

Redis is an open source (BSD licensed), in-memory data structure store, used as a database and cache. It supports data structures such as strings, hashes, lists, sets etc.

You can download redis server as well as client for linux here : Redis for linux

Redis for windows can be downloaded here : Redis for windows. Once downloaded and unzipped run redis-server.exe comman to start the redis server.

Now we will use jedis (java redis client) to communicate with this redis server. It can be downloaded here :Jedis – The java client for redis

Create jedis client by connecting it to localhost. You can give IP address in case Redis server is running on some other machine

Jedis jedis = new Jedis("localhost");

Saving simple key-value pair

jedis.set("simple-key","simple-value")
jedis.get("simple-key")

Pushing a list to redis and fetching back that list

jedis.lpush("tutorial-list", "Redis"); 
jedis.lpush("tutorial-list", "Mongodb"); 
jedis.lpush("tutorial-list", "Mysql"); 
 
List<String> list = jedis.lrange("tutorial-list", 0, 5);
for(int i = 0; i<list.size(); i++) { 
       System.out.println("Stored string in redis:: "+list.get(i)); 
}

Storing a map

 Map<String,String> map = new HashMap<String,String>();
    map.put("India", "MS Dhoni");
    map.put("Australia", "Steve Smith");
    jedis.hmset("mapKey", map);
 
    System.out.println(jedis.hmget("mapKey", "India","Australia"));

Adding a set of unique values

jedis.sadd("setKey", "value1");
    jedis.sadd("setKey", "value2");
    jedis.sadd("setKey", "value2");
 
    System.out.println(jedis.smembers("setKey"));

Setting max-age of the key

jedis.expire("key", 2);

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *