Using Jedis

Jedis is one of Redis clients written in Java, though I have not tried using any other client. It is very easy to configure Jedis and use it as a client. Lets quickly jump over to the code part and understand things.
Using Maven dependency:
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.6.0</version>
</dependency>
Problem Statement: – We have to add items to a sorted set on basis of some random scores attached to the values. Also there has to be maximum of 10 items present in the sorted set. We will use the functions zadd and zremrandeByScore.
Some Java code:
 Initializing the Redis Client – Our server is up on localhost:6379 (default). For multiple servers running we can add them to pool.
public RedisCacheManager() {
    List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
    for (String host : HOSTNAMES) {
        JedisShardInfo si = new JedisShardInfo(host, Constants.CACHE_PORT);
        shards.add(si);
        LOGGER.info("Added host to shard: " + host);
    }
    GenericObjectPoolConfig jedisConfig = new GenericObjectPoolConfig();
    JEDIS_POOL = new ShardedJedisPool(jedisConfig, shards);
}
Pushing items in a sorted set –
public boolean pushActivity(String activity, String activityId, double score, int ttl) {
    ShardedJedis redis = JEDIS_POOL.getResource();
    String redisKey = null;
    try {
        redisKey = activityId;
        redis.zadd(redisKey, score, activity);
        if (ttl > 0) {
            redis.expire(redisKey, ttl);
        }
        Long count = redis.zcount(redisKey, Double.MIN_VALUE, Double.MAX_VALUE);
        if (count > 10) {
            redis.zremrangeByScore(redisKey, Double.MIN_VALUE, count - 10);
        }
        return true;
    } catch (Exception e) {
        LOGGER.error("Unable to enter data into redis for - " + redisKey + " with activity - " + activity, e);
    } finally {
        JEDIS_POOL.returnResource(redis);
    }
    return false;
}
Retrieving item from Redis –
public Set<String> retrieveItem(int activityId, int maxIndex) {
    ShardedJedis redis = JEDIS_POOL.getResource();
    String redisKey = activityId;
    Set<String> redisValue = Collections.emptySet();
    try {
        redisValue = redis.zrange(redisKey, 0, maxIndex);
    } catch (Exception e) {
        LOGGER.error("Unable to fetch data from redis for - " + redisKey, e);
    } finally {
        JEDIS_POOL.returnResource(redis);
    }
    return redisValue;
}

One thought on “Using Jedis

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s