Intro to Jedis Part 1

Intro to Jedis Part 1

Jedis is a client library in Java for Redis.
The popular in-memory data structure store that can persist on disk as well.

Maven Dependencies:

redis.clientsjedis3.3.0

Redis Installation:

You will need to install and fire up one of the latest versions of Redis.
We are running the latest stable version at this moment (3.2.1), but any post 3.x version should be okay.

After that we can directly dive in and connect to it from our Java code:
Jedis jedis = new Jedis();

Strings:

Strings are the most basic kind of Redis value, useful for when you need to persist simple key-value data types:
jedis.set(“events/city/ip”, “55.44.33.22”);
String cachedResponse = jedis.get(“events/city/ip”);

Lists:

Redis Lists are simply lists of strings, sorted by insertion order and make it an ideal tool to implement, for instance, message queues:
jedis.lpush(“queue#tasks”, “firstTask”);
jedis.lpush(“queue#tasks”, “secondTask”);

String task = jedis.rpop(“queue#tasks”);
The variable task will hold the value firstTask. Remember that you can serialize any object and persist it as a string,
so messages in the queue can carry more complex data when required.

Sets:

Redis Sets are an unordered collection of Strings that come in handy when you want to exclude repeated members:
jedis.sadd(“nicknames”, “nickname#1”);
jedis.sadd(“nicknames”, “nickname#2”);
jedis.sadd(“nicknames”, “nickname#1”);

Setnicknames = jedis.smembers(“nicknames”);
boolean exists = jedis.sismember(“nicknames”, “nickname#1”);
The Java Set nicknames will have a size of 2, the second addition of nickname#1 was ignored.
Also, the exists variable will have a value of true, the method sismember enables you to check for the existence of a particular member quickly.

Hashes:

Redis Hashes are mapping between String fields and String values:
jedis.hset(“user#1”, “name”, “Peter”);
jedis.hset(“user#1”, “job”, “politician”);

String name = jedis.hget(“user#1”, “name”);

Map<String, String> fields = jedis.hgetAll(“user#1”);
String job = fields.get(“job”);
As you can see, hashes are a very convenient data type when you want to access object’s properties individually
since you do not need to retrieve the whole object.

Sorted Sets:

Sorted Sets are like a Set where each member has an associated ranking, that is used for sorting them:
Map<String, Double> scores = new HashMap<>();

scores.put(“PlayerOne”, 3000.0);
scores.put(“PlayerTwo”, 1500.0);
scores.put(“PlayerThree”, 8200.0);

scores.entrySet().forEach(playerScore -> {
jedis.zadd(key, playerScore.getValue(), playerScore.getKey());
});

String player = jedis.zrevrange(“ranking”, 0, 1).iterator().next();
long rank = jedis.zrevrank(“ranking”, “PlayerOne”);

The variable player will hold the value PlayerThree because we are retrieving the top 1 player and he is the one with the highest score.
The rank variable will have a value of 1 because PlayerOne is the second in the ranking and the ranking is zero-based.